使用toHaveBeenNthCalledWith时反应Jest测试错误

时间:2019-02-05 17:30:49

标签: reactjs jestjs enzyme

我正在追踪Jest的documentation,但是我无法解决以下错误。 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] }

toHaveBeenCalledNthWith Test

const dummyFunction = jest.fn();

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

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

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

toHaveBeenNthCalledWith的发布版本为Jest,版本为23.0.0,因此,如果您使用的是Jest的早期版本,则会看到该错误。

请注意,toHaveBeenNthCalledWith只是syntactic sugar for using 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