这是解决方案,使用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