为什么我不能在 jasmine 的 expectAsync 中使用匿名函数?

Why can't I use an anonymous function inside jasmine's expectAsync?

我正尝试在 Jasmine 中为我的 Nodejs Mongoose 模型进行单元测试。一切正常,除非我将代码从功能块转移到匿名/箭头功能。我不明白为什么它不能使用匿名/箭头函数。

这是我的基本规格文件:

const MongoDbTest = require('../lib/mongodb-tests.lib');
const Info = require("../models/info.model");

async function addTupleWithoutValue() {
  await new Info({ name: 'trududu' }).save();
}

describe("Le modèle Info", () => {
  const mongod = new MongoDbTest();

  beforeAll(async () => {
    await mongod.connect(); // This takes care of connecting to the database, etc.
  } );

  afterAll(async () => {
    await mongod.close(); // This takes care of closing the connection, etc.
  } );

  // ... other tests removed

  it("a absolument besoin du champ 'value'", async () => {
    await expectAsync(async function() {
      await new Info({ name: 'trududu' }).save();
    } ).toBeRejectedWithError(/value: Path `value` is required/); // This does not work

    await expectAsync(addTupleWithoutValue()).toBeRejectedWithError(/value: Path `value` is required/); // this works
  } );
} );

这是我的模型:

const mongoose = require('mongoose');
const Mixed = mongoose.Mixed;

const InfoSchema = new mongoose.Schema( {
  name: { type: String, unique: true },
  value: { type: Mixed, required: true }
} );

module.exports = mongoose.model('Info', InfoSchema);

当我使用匿名函数(或箭头函数)时,Jasmine 给我以下错误消息: Error: Expected toBeRejectedWithError to be called on a promise. 查看 Jasmine 的源代码,值 return 由函数编辑由 function(obj) { return !!obj && j$.isFunction_(obj.then); } 检查。这是否意味着匿名函数 return 是一种不同的承诺?

嗯,事实证明我忽略了匿名函数和函数块之间的细微差别。你发现了吗?这是:

await expectAsync(async function() {
  await new Info({ name: 'trududu' }).save();
} ).toBeRejectedWithError(/value: Path `value` is required/); // This does not work

await expectAsync(addTupleWithoutValue()).toBeRejectedWithError(/value: Path `value` is required/); // this works

第二个有一个额外的 () 这意味着函数被调用并且 returns 一个承诺。第一个只是函数定义,这意味着 toBeRejectedWithError 失败,因为它需要一个承诺,而不是一个函数。

通过在匿名函数定义后添加(),将其更改为函数call(返回一个promise),一切正常魅力。

我在发布问题之前解决了这个问题,但由于没有找到任何类似问题而决定完成发布。我希望这对其他开发人员有所帮助。