reactjs - 期望在反应测试库中使用参数调用笑话模拟失败
问题描述
我希望这个测试能够通过,但它失败了:
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},
我不确定如何让它通过或进一步了解问题所在?
解决方案
在检查最后一次函数调用的参数时,可以使用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),
})
)
推荐阅读
- c++ - 如何防止写入 0 而不是未输入的数组元素?
- c - 如何使 C 包装器 API 线程安全?
- c# - C#,如何设计多个接口以访问相同的委托?
- javascript - 如何将有序 Map 构造为持久数据结构?
- c# - 我无法读取字典中的结构值
- sql-server - Windows 调试器(Windbg)无法为 SQL 转储文件加载符号
- protege - Protege 中旧类与其子类之间的新类
- java - HTTP 状态 404 - 未找到 -hibernate-spring mvc--
- vue.js - Vuejs 中的 ESLint + Prettier 警告
- spacy - 在法国简历中为 NER 训练一个 spacy 模型没有给出任何结果