运行测试时未实现 window.alert

IT技术 reactjs jestjs
2021-04-28 16:51:51

我正在尝试使用 jest 测试仪进行一些实验以进行react,当我执行 an 时npm test,测试通过,但出现此错误:

Snapshots:   0 total
  console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Not implemented: window.alert

我知道这是因为我在代码中调用了警报,因为如果我注释掉警报调用,我就不会收到错误消息。

我尝试了此处提到的解决方案但仍然出现错误。有什么办法可以消除这个错误,同时仍然在我的代码中保留警报调用?

这是测试:

it('renders without crashing', () => {
  jest.spyOn(window, 'alert').mockImplementation(() => {});
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});
1个回答

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