我有一个按钮,上面有用ReactJS代码定义的“下载”文本。现在,我想编写一个单元测试,以检查该函数在单击此按钮时是否被调用。我写了一个单元测试,但它不起作用。
import * as FileSaver from "file-saver"
it('File has to be saved when clicked on the "Download" button', () => {
jest.mock('file-saver', ()=>({saveAs: jest.fn()}));
fireEvent.click(component.getByText("Download"));
expect(FileSaver.saveAs).toBeCalled();
})我得到了一个错误:
Error: expect(received).toBeCalled()
Matcher error: received value must be a mock or spy function
Received has type: function
Received has value: [Function anonymous]指向expect(FileSaver.saveAs).toBeCalled();行。
怎么了?
发布于 2022-04-01 11:04:43
因此,正如我在注释中所说的,您必须将jest.mock('file-saver', ()=>({saveAs: jest.fn()}))从测试的主体移到文件的顶部,就在导入下面。它的原因实际上在文档这里中得到了回答,但是要结束它:
在您的测试文件中,您使用的是import语句,在任何代码有机会运行之前,该语句会在启动时启动。然后尝试模拟file-saver,但是它已经用实际的实现导入了,而不是模拟的。如果您指示jest在文件顶部模拟模块,它将自动将jest.mock调用提升到模块的顶部,这样您的函数exportToExcel将接收模拟的file-saver而不是真正的file-saver。
但是,如果出于某种奇怪的原因,您真的想在测试的主体中模拟file-saver,那么需要模拟file-saver,那么在测试中包括所有使用file-saver的模块,如下所示:
it('File has to be saved when clicked on the Export button', () => {
jest.mock('file-saver', ()=> ({ saveAs: jest.fn() }));
const component = require('/path/to/tested/componetn/on/which/click/event/is/fired');
const FileSaver = require('file-saver');
fireEvent.click(component.getByText("Download"));
expect(FileSaver.saveAs).toBeCalled();
})https://stackoverflow.com/questions/71691490
复制相似问题