Jest中的以下测试不应通过:
const targetFile = require("../targetFile.js");
fetch = jest.fn(() => Promise.resolve('file scoped default value'));
test('diffFileFetch', () => {
fetch.mockImplementation(() => new Promise((resolve, reject) => {
resolve('wrong value');
}));
targetFile.diffFileFetch()
.then(async data => {
await expect(data).toEqual('correct value');
})
.catch(e => console.log(e, `=====e=====`));
});
捕获块触发,但测试仍通过。是什么原因造成的,应该如何解决?
PASS
views/admin/__tests__/CurrentCouponListingSection.test.js
✓ diffFileFetch (6ms)
console.log views/admin/__tests__/testFile.test.js:59
{ Error: expect(received).toEqual(expected) // deep equality
Expected: "correct value"
Received: "wrong value"
at targetFile.diffFileFetch.then (/var/www/html/wptest2/wp-content/plugins/fvc/views/admin/__tests__/testFile.test.js:58:1)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
matcherResult:
{ actual: 'wrong value',
expected: 'correct value',
message: [Function],
name: 'toEqual',
pass: false } } '=====e====='
也尝试过
从.then()中删除异步/等待。没什么。
答案 0 :(得分:1)
在Promise
回调运行之前,测试已经完成,因此可以通过...然后记录错误。
如果测试包含异步代码,则您需要使用done
:
test('diffFileFetch', done => { // <= use done
fetch.mockImplementation(() => new Promise((resolve, reject) => {
resolve('wrong value');
}));
targetFile.diffFileFetch()
.then(data => {
expect(data).toBe('correct value');
done(); // <= now call done
})
});
...返回Promise
:
test('diffFileFetch', () => {
fetch.mockImplementation(() => new Promise((resolve, reject) => {
resolve('wrong value');
}));
return targetFile.diffFileFetch() // <= return the Promise
.then(data => {
expect(data).toBe('correct value');
})
});
...或使用async
测试函数和await
Promise
:
test('diffFileFetch', async () => { // <= async test function
fetch.mockImplementation(() => new Promise((resolve, reject) => {
resolve('wrong value');
}));
const data = await targetFile.diffFileFetch() // <= await the Promise
expect(data).toBe('correct value');
});