cod*_*123 5 javascript mocking reactjs jestjs enzyme
我希望能够测试这个Swal()函数是否被调用。
它被嘲笑,但我不熟悉 Jest 嘲笑库。
这是我的测试设置文件中:
jest.mock('sweetalert2', () => {
return {
Swal: () => {},
};
});
Run Code Online (Sandbox Code Playgroud)
所以我只想返回一个函数。
在我的组件中,Swal 的调用方式如下:
doSomething = () => {
Swal({
title: 'Could not log in',
text: error.message,
type: 'error',
});
};
Run Code Online (Sandbox Code Playgroud)
我认为我的模拟需要返回一个命名方法,因此我可以监视它并检查它是否被调用。
我的测试:
import Swal from 'sweetalert2';
describe('Login Container', () => {
it('calls Swal', () => {
doSomething();
var swalSpy = jest.spyOn(Swal, 'Swal');
expect(swalSpy).toHaveBeenCalled();
});
});
Run Code Online (Sandbox Code Playgroud)
错误:
expect(jest.fn()).tohavebeencalled();
Run Code Online (Sandbox Code Playgroud)
当测试失败时,我应该如何设置我的模拟和间谍
我希望模拟工厂需要返回一个对象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();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4668 次 |
| 最近记录: |