我正尝试在Jest和Enzyme中为我的React App设置一些简单的测试。我正在使用shallow
来渲染应用程序的主容器,但是似乎正在渲染子级和下面的所有子级。
● Test suite failed to run
TypeError: Cannot read property 'NaN' of undefined
7 | export function getRandomColor() {
8 | console.log(colors);
> 9 | return colorsKeys[Math.floor(Math.random() * colorsLength)];
| ^
10 | }
11 |
12 | export function determineColor(genotype) {
at getRandomColor (src/utils/determineColor.js:9:19)
at Object.<anonymous> (src/exampleState.js:10:16)
at Object.<anonymous> (src/reducers/flowersReducer.js:1:1)
at Object.<anonymous> (src/reducers/indexReducer.js:2:1)
at Object.<anonymous> (src/index.js:14:1)
at Object.<anonymous> (src/utils/determineColor.js:5:1)
at Object.<anonymous> (src/components/NewFlowerFromPunnettButton.js:4:1)
at Object.<anonymous> (src/components/Dashboard.js:2:1)
at Object.<anonymous> (src/App.jsx:6:1)
at Object.<anonymous> (test/App.test.js:4:1)
每个Enzyme docs“浅表渲染有助于将组件作为一个单元进行测试,并确保您的测试不会间接断言子组件的行为。”
This SO answer似乎澄清了shallow
“将呈现其所有子项以及所有子项,依此类推。”
//App.test.js
import React from "react";
// shallow prevents rendering of sub components????
import { shallow, mount, render } from "enzyme";
import App from "../src/App";
describe("<App />", () => {
const app = shallow(<App />);
it("Should render ", () => {
expect(app).toMatchSnapShot();
});
it("Should have <Punnett/> <Dashboard/> and <FlowerTable />", () => {
expect(app.find("<Punnett />")).toBeTruthy();
expect(app.find("<Dashboard/>")).toBeTruthy();
expect(app.find("<FlowerTable />")).toBeTruthy();
});
});
//App.jsx
import React, { Component, Fragment } from "react";
import "./css/App.css";
import Punnett from "./components/Punnett";
import FlowerTable from "./components/FlowerTable/FlowerTable";
import Dashboard from "./components/Dashboard";
class App extends Component {
render() {
return (
<Fragment>
<div className="App">
<Punnett />
<Dashboard />
</div>
<div className="App">
<FlowerTable display={true} />
</div>
</Fragment>
);
}
}
export default App;
// determineColor.js
import { colors } from "../types/colors";
const colorsKeys = Object.keys(colors);
const colorsLength = colorsKeys.length;
import { store } from "../index";
export function getRandomColor() {
console.log(colors);
return colorsKeys[Math.floor(Math.random() * colorsLength)];
}
我期望浅层不能渲染子级,或者如果预期的行为是渲染所有子级,则子级能够正确导入其模块。将shallow
换为render
会导致相同的错误。
通过在https://github.com/nodes777/flower-game-phaser3上克隆并运行npm run test
可以复制
答案 0 :(得分:1)
shallow
仅渲染子级,这是正确的。根本原因:似乎"./components/Dashboard";
内有可以在import
上运行的代码-一些执行而不是声明的顶级代码。
您可以更改Dashboard
而不这样做,或者提供需要的数据,或者在可能直接或间接导入的每个测试中明确地模拟它:
App.test.js:
jest.mock('./components/Dashboard');
如果您选择以后的方法,则可以考虑通过创建components/Dashboard/__mocks__/index.jsx
(或Dashboard中的文件名如何)来进行自动模拟,但是要注意bug in jest,这会禁止您使用多个以上的{{1 }},无论它们位于不同的文件夹中