【发布时间】:2021-02-11 10:15:44
【问题描述】:
我正在尝试在 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 的源代码,函数返回的值由 function(obj) { return !!obj && j$.isFunction_(obj.then); } 检查。这是否意味着匿名函数返回不同类型的承诺?
【问题讨论】:
标签: javascript node.js unit-testing mongoose jasmine