运行测试时未实现window.alert [英] window.alert not implemented when running tests
问题描述
我正在尝试用开玩笑的测试器进行反应,当我执行npm test
时,测试通过了,但是出现了这个错误:
I am trying to experiment some with the jest tester for react and when I do an npm test
, the test passes ok, but I get this error:
Snapshots: 0 total
console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Not implemented: window.alert
我知道这是由于我在代码中发出了警报呼叫,因为如果我对警报呼叫进行注释,则不会收到错误消息.
I know this is due to the fact that I an alert call in my code because if I comment that alert call out I don't get the error.
我尝试了此处但我仍然收到错误.我有什么办法可以消除此错误,同时仍将警报调用保留在我的代码中?
I tried the solution mentioned here but I still get the error. Is there any way I can eliminate this error while still keeping the alert call in my code?
这是测试:
it('renders without crashing', () => {
jest.spyOn(window, 'alert').mockImplementation(() => {});
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
推荐答案
以下是解决方案,请使用jest.fn()
而不是jest.spyOn
:
Here is the solution, use jest.fn()
instead of using 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%:
Unit test result with 100% coverage:
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
这篇关于运行测试时未实现window.alert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!