Javascript fn()模拟函数为';我没有第二次打电话
我正在测试我们项目的一个功能,遇到了一个奇怪的问题,我不知道如何解决这个问题Javascript fn()模拟函数为';我没有第二次打电话,javascript,jestjs,Javascript,Jestjs,我正在测试我们项目的一个功能,遇到了一个奇怪的问题,我不知道如何解决这个问题 jest-v 24.8.0 节点-v v10.14.2 输出: ● test case › should pass expect(jest.fn()).nthCalledWith(expected) Expected mock function second call to have been called with: ["fn1 call 2"] But it was n
jest-v
24.8.0
节点-v
v10.14.2
输出:
● test case › should pass
expect(jest.fn()).nthCalledWith(expected)
Expected mock function second call to have been called with:
["fn1 call 2"]
But it was not called.
19 | expect(fn2).toBeCalledWith('fn2 call 1');
20 | expect(fn1).nthCalledWith(1,'fn1 call 1');
> 21 | expect(fn1).nthCalledWith(2,'fn1 call 2');
| ^
22 | })
23 | });
24 |
at Object.nthCalledWith (test.js:21:25)
console.log test.js:7
then was called
如果我将fn1替换为:
(args)=>console.log(args)
我明白了:
console.log test.js:13
fn1 call 1
console.log test.js:13
fn1 call 2
console.log test.js:7
then was called
因此,我使用jest.fn()的方式可能有一些错误
有人能帮我解决这个问题吗?您收到此错误的原因是操作
返回一个承诺,而您没有等待该承诺的结果;当第二次调用fn1
时,由于这一行expect(fn1)。n使用(2,'fn1 call 2')
调用,因此您会看到错误。另外,在jest.fn().mockResolvedValue()中调用Promise.resolve('test')
代码>是冗余的
要解决此问题,您需要等待操作的结果:
describe('test case', () => {
it('should pass', async () => {
const fn1 = jest.fn();
const fn2 = jest.fn()
.mockResolvedValue('test');
await action(fn1, fn2);
expect(fn2)
.toBeCalledWith('fn2 call 1');
expect(fn1)
.nthCalledWith(1, 'fn1 call 1');
expect(fn1)
.nthCalledWith(2, 'fn1 call 2');
});
});
另一种方法:
describe('test case', () => {
it('should pass', (done) => {
const fn1 = jest.fn();
const fn2 = jest.fn()
.mockResolvedValue(Promise.resolve('test'));
action(fn1, fn2)
.then(() => {
expect(fn2)
.toBeCalledWith('fn2 call 1');
expect(fn1)
.nthCalledWith(1, 'fn1 call 1');
expect(fn1)
.nthCalledWith(2, 'fn1 call 2');
done();
});
});
});
您收到此错误的原因是操作
返回承诺,并且您没有等待该承诺的结果;当第二次调用fn1
时,由于这一行expect(fn1)。n使用(2,'fn1 call 2')
调用,因此您会看到错误。另外,在jest.fn().mockResolvedValue()中调用Promise.resolve('test')
代码>是冗余的
要解决此问题,您需要等待操作的结果:
describe('test case', () => {
it('should pass', async () => {
const fn1 = jest.fn();
const fn2 = jest.fn()
.mockResolvedValue('test');
await action(fn1, fn2);
expect(fn2)
.toBeCalledWith('fn2 call 1');
expect(fn1)
.nthCalledWith(1, 'fn1 call 1');
expect(fn1)
.nthCalledWith(2, 'fn1 call 2');
});
});
另一种方法:
describe('test case', () => {
it('should pass', (done) => {
const fn1 = jest.fn();
const fn2 = jest.fn()
.mockResolvedValue(Promise.resolve('test'));
action(fn1, fn2)
.then(() => {
expect(fn2)
.toBeCalledWith('fn2 call 1');
expect(fn1)
.nthCalledWith(1, 'fn1 call 1');
expect(fn1)
.nthCalledWith(2, 'fn1 call 2');
done();
});
});
});