我希望能够测试是否调用此 Swal()
函数。
它被 mock 了,但我不熟悉 Jest mock 库。
这是在我的测试设置文件中:
jest.mock('sweetalert2', () => {
return {
Swal: () => {},
};
});
所以我只想返回一个函数。
在我的组件中,Swal 的调用方式如下:
doSomething = () => {
Swal({
title: 'Could not log in',
text: error.message,
type: 'error',
});
};
我认为我的模拟需要返回一个命名方法,因此我可以监视它并检查它是否被调用。
我的测试:
import Swal from 'sweetalert2';
describe('Login Container', () => {
it('calls Swal', () => {
doSomething();
var swalSpy = jest.spyOn(Swal, 'Swal');
expect(swalSpy).toHaveBeenCalled();
});
});
错误:
expect(jest.fn()).tohavebeencalled();
当测试失败时,我应该如何设置我的模拟和 spy
最佳答案
我希望模拟工厂需要返回一个具有 default
的对象(因为 import Swal 正在导入默认模块)。像这样的东西(演示 sweetalert v1):
// extract mocked function
const mockAlert = jest.fn()
// export mocked function as default module
jest.mock('sweetalert', () => ({
default: mockAlert,
}))
// import the module that you are testing AFTER mocking
import doSomethingThatAlerts from './doSomethingThatAlerts'
// test suite loosely copied from OP
describe('Login Container', () => {
it('calls Swal', () => {
doSomethingThatAlerts();
// test mocked function here
expect(mockAlert).toHaveBeenCalled();
});
});
关于javascript - 如何使用 Jest 模拟第三方包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50746450/