我有一个非常简单的测试
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",
答案 0 :(得分:0)
经过一番痛苦,我用一个模拟解决了这个问题。
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);
});
这通过了我的测试,尽管vs code
仍在抱怨
mockImplementation在()=> void
类型上不存在