我有以下单元测试:
var { Mockgoose } = require("mockgoose");
var mongoose = require("mongoose");
var Transaction = require("./transaction");
var mockgoose = new Mockgoose(mongoose);
describe("transaction", function() {
afterEach(function() {
return mockgoose.helper.reset();
});
afterAll(function() {
const { connections } = mongoose;
const { childProcess } = mockgoose.mongodHelper.mongoBin;
// kill mongod
childProcess.kill();
// close all connections
for (const con of connections) {
return con.close();
}
return mongoose.disconnect();
});
test("category is required", function() {
expect.assertions(1);
return mockgoose.prepareStorage().then(function() {
mongoose.connect("mongodb://foobar/baz");
return mongoose.connection.on("connected", function() {
var mockTransaction = new Transaction({
amount: 25,
comment: "Gas money, Petrol.",
tags: ["Gas", "Car", "Transport"],
currency: "EUR"
});
return mockTransaction.save(function(err, savedTransaction) {
expect(err.errors.category.properties.message).toBe(
"Category is required."
);
});
});
});
});
test("category should match one of the predefined categories", function() {
expect.assertions(1);
return mockgoose.prepareStorage().then(function() {
mongoose.connect("mongodb://foobar/baz");
return mongoose.connection.on("connected", function() {
var mockTransaction = new Transaction({
category: "dsawdsfawfsaf",
amount: 25,
comment: "Gas money, Petrol.",
tags: ["Gas", "Car", "Transport"],
currency: "EUR"
});
return mockTransaction.save(function(err, savedTransaction) {
expect(err.errors.category.properties.message).toBe(
"{VALUE} is not a valid category."
);
});
});
});
});
});
现在,如果我仅运行其中一项测试,则所有测试均会通过,但是当我同时运行它们时,会出现以下错误:
●交易›类别应与预定义之一匹配 类别
expect.assertions(1) Expected one assertion to be called but received two assertion calls. 43 | 44 | test("category should match one of the predefined categories", function() { > 45 | expect.assertions(1); | ^ 46 | return mockgoose.prepareStorage().then(function() { 47 | mongoose.connect("mongodb://foobar/baz"); 48 | return mongoose.connection.on("connected", function() {
不是每个测试都有自己的断言和期望吗?
答案 0 :(得分:0)
我在代码中发现,当我同时使用“异步”和“同步”测试来测试异步功能时,就会出现此问题。
我使用jest Expect()以“同步方式”测试了异步函数。解决/拒绝了导致问题的API。必须以异步等待样式重写测试。那解决了这个问题。
describe('asyncSum()', () => {
test('"broken" sync test', () => {
expect(asyncSum(2, 2)).resolves.toEqual(4); // This line causes the issue incorrect assertion count
})
test('async test resolves example', async () => {
expect.assertions(1);
const sum = await asyncSum(2, 2);
expect(sum).toEqual(4);
})
test('async test reject example', async () => {
expect.assertions(1);
let error;
try {
await asyncSum(2);
} catch (err) {
error = err;
}
expect(error.message).toEqual('Missing 2nd parameter')
}
})