我正在尝试用开玩笑的测试器进行反应,当我进行npm test
时,测试通过了,但是出现了这个错误:
Snapshots: 0 total
console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Not implemented: window.alert
我知道这是由于我在代码中发出了警报调用,因为如果我对警报调用进行注释,则不会收到错误消息。
我尝试了提到的here解决方案,但仍然收到错误消息。有什么方法可以消除此错误,同时仍将警报调用保留在我的代码中?
这是测试:
it('renders without crashing', () => {
jest.spyOn(window, 'alert').mockImplementation(() => {});
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
答案 0 :(得分:0)
这是解决方案,请使用jest.fn()
而不是jest.spyOn
:
index.tsx
:
import React, { Component } from 'react';
class App extends Component {
componentDidMount() {
window.alert('haha');
}
render() {
return <div></div>;
}
}
export default App;
index.spec.tsx
:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './';
describe('App', () => {
it('renders without crashing', () => {
window.alert = jest.fn();
const div = document.createElement('div');
ReactDOM.render(<App />, div);
expect(window.alert).toBeCalledWith('haha');
ReactDOM.unmountComponentAtNode(div);
});
});
覆盖率100%的单元测试结果:
PASS src/stackoverflow/55787988/index.spec.tsx (9.069s)
App
✓ renders without crashing (26ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.453s, estimated 13s
依赖版本:
"jest": "^24.9.0",
"jsdom": "^15.2.0",
"react": "^16.11.0",
"react-dom": "^16.11.0",
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55787988