使用 toHaveBeenNthCalledWith 时反应 Jest 测试错误

CWS*_*tes 3 reactjs jestjs enzyme

我正在关注 Jest 的文档,但是我无法解决以下错误。expect(dummyFunction).toHaveBeenNthCalledWith is not a function

除非我遗漏了什么,我很确定我的dummyFunction设置正确地作为jest.fn(). 我什至dummyFunction在我的测试中使用它之前安慰了它的输出,这就是输出。

dummyFunction console.log 输出

    { [Function: mockConstructor]
      _isMockFunction: true,
      getMockImplementation: [Function],
      mock: [Getter/Setter],
      mockClear: [Function],
      mockReset: [Function],
      mockReturnValueOnce: [Function],
      mockReturnValue: [Function],
      mockImplementationOnce: [Function],
      mockImplementation: [Function],
      mockReturnThis: [Function],
      mockRestore: [Function] }
Run Code Online (Sandbox Code Playgroud)

toHaveBeenCalledNthWith 测试

const dummyFunction = jest.fn();

expect(dummyFunction).toHaveBeenCalledTimes(2); // pass

expect(dummyFunction).toHaveBeenNthCalledWith(1, { foo: 'bar' }); // error
expect(dummyFunction).toHaveBeenNthCalledWith(2, { please: 'work' });
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助。

Bri*_*ams 6

toHaveBeenNthCalledWith是在23.0.0Jest版中发布的,因此如果您使用的是早期版本的.Jest

请注意,这toHaveBeenNthCalledWith只是使用的语法糖,spy.mock.calls[nth]因此如果您使用的是早期版本,则Jest可以执行以下操作:

const dummyFunction = jest.fn();

dummyFunction({ foo: 'bar' });
dummyFunction({ please: 'work' });

expect(dummyFunction).toHaveBeenCalledTimes(2); // pass

expect(dummyFunction.mock.calls[0]).toEqual([{ foo: 'bar' }]); // pass
expect(dummyFunction.mock.calls[1]).toEqual([{ please: 'work' }]); // pass
Run Code Online (Sandbox Code Playgroud)