Rya*_*P13 5 file-upload mocking reactjs jestjs react-testing-library
我希望这个测试通过,但它失败了:
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,
});
});
Run Code Online (Sandbox Code Playgroud)
Jest 报告说:
expect(jest.fn()).toHaveBeenCalledWith(...expected)
- Expected
+ Received
- {"item": [Function item], "length": 1},
+ {"item": [Function item], "length": 1},
Run Code Online (Sandbox Code Playgroud)
我不知道如何让它通过或深入了解出了什么问题?
当检查最后一个函数调用的参数时,可以使用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),
})
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1216 次 |
| 最近记录: |