0

我有一个非常简单的测试

    const div = document.createElement("div");
    ReactDOM.render(<App />, div);
    ReactDOM.unmountComponentAtNode(div);

此代码失败:

componentDidMount() {
    const ProgressBar = require('progressbar.js');
    /* istanbul ignore next */
    const bar = new ProgressBar.Line('#progressDiv', {
        strokeWidth: 2,
        easing: 'easeInOut',

错误:

● renders without crashing

Container does not exist: #progressDiv

   6 |         const ProgressBar = require('progressbar.js');
   7 |         /* istanbul ignore next */
>  8 |         const bar = new ProgressBar.Line('#progressDiv', {
     |                     ^
   9 |             strokeWidth: 2,

容器确实存在。

我认为这是一个常见问题,因为 ComponentDidMount 在渲染之前执行?

运行命令:

npm test=>"test": "react-scripts test --watchAll=false"

版本:

"react-scripts": {
  "version": "2.1.5",
  "jest": "23.6.0",
4

1 回答 1

0

after much pain i solved this using a mock.

jest.mock('../components/app/App');

it("renders without crashing", () => {

    const spy = jest.fn()
    App.prototype.componentDidMount.mockImplementation(() => spy())

    const div = document.createElement("div");
    ReactDOM.render(<App />, div);
    ReactDOM.unmountComponentAtNode(div);
});

this passes my tests, although vs code still complains

mockImplementation does not exist on type () => void

于 2019-04-24T18:14:01.237 回答