我正在尝试在 Jest 和 Enzyme 中为我的 React 应用程序设置一些简单的测试。我正在使用 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
来重现
最佳答案
shallow
只渲染子项,你是对的。根本原因:似乎 "./components/Dashboard";
内部有在 import
上运行的代码 - 一些顶级代码是执行而不是声明。
您可以更改Dashboard
而不这样做,或者提供它工作所需的数据,或者在可能直接或间接导入它的每个测试中显式模拟它:
App.test.js:
jest.mock('./components/Dashboard');
如果您选择后面的方法,您可以考虑通过创建 components/Dashboard/__mocks__/index.jsx
(或者 Dashboard 的文件名如何)来进行自动模拟,但要注意 bug in jest不允许您对多个 index.js
使用 automock,无论它们位于不同的文件夹中
关于javascript - 酵素的浅薄是渲染 child 的 child 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56996300/