首页 > 解决方案 > 期望在反应测试库中使用参数调用笑话模拟失败

问题描述

我希望这个测试能够通过,但它失败了:

it('should consume files on drop', () => {
  const mock = jest.fn();
  const file = new File(['file'], 'file.txt', { type: 'text/plain' });
  const fileList = [file];

  render(<DropZone onDocumentDrop={mock} />);

  const dropZone = screen.getByTestId('dropZone');
  const dropEvent = createEvent.drop(dropZone);

  Object.defineProperty(dropEvent, 'dataTransfer', {
    value: {
      files: {
        item: (index: number) => fileList[index],
        length: fileList.length,
      },
    },
  });

  fireEvent(dropZone, dropEvent);

  expect(dropZone).toBeInTheDocument();
  expect(mock).toHaveBeenCalled();
  expect(mock).toHaveBeenCalledWith({
    item: (index: number) => fileList[index],
    length: 1,
  });
});

Jest 报告说:

expect(jest.fn()).toHaveBeenCalledWith(...expected)

- Expected
+ Received

- {"item": [Function item], "length": 1},
+ {"item": [Function item], "length": 1},

我不确定如何让它通过或进一步了解问题所在?

标签: reactjsfile-uploadjestjsmockingreact-testing-library

解决方案


在检查最后一次函数调用的参数时,可以使用expect.objectContaining()来匹配接收到的对象。

您也可以使用lastCalledWith()代替toHaveBeenCalledWith(). 它们都是相同的,但我个人更喜欢前者,因为它更短且更易于阅读。

const item = (index: number) => []
const args = {
  length: 1,
  item,
}

const mock = jest.fn()

mock(args)

expect(mock).lastCalledWith(
  expect.objectContaining({
    length: expect.any(Number), // or 1 if you know the exact value
    item: expect.any(Function),
  })
)

推荐阅读