如何测试一个组件是否被 jest 和 enzyme 渲染?
How to test if a component is rendered or not by jest and enzyme?
我正在尝试在 React 中学习 tdd。我有一个父组件,它从应用程序组件获取道具,并根据道具渲染 child1 组件或 child2 组件。这是我的反应文件:
App.js
import './App.css';
import Parent from './Parent';
function App() {
return (
<div className="App">
<Parent number={"one"} word={"hello"}/>
{/* can be one or two */}
</div>
);
}
export default App;
Parent.js
import React from 'react';
import Child1 from './Child1';
import Child2 from './Child2';
function Parent({number,word}) {
return (
<div className="Parent" data-testid="parent-test">
{number === 'one' &&
<Child1 />
}
{number === 'two' &&
<Child2/>
}
</div>
);
}
export default Parent;
child1.js
import React from 'react';
function Child1() {
return (
<div>
I am Child1
</div>
);
}
export default Child1;
child2.js
import React from 'react';
function Child2() {
return (
<div>
I am Child2
</div>
);
}
export default Child2;
`
How can I write a test using Jest and enzyme to check in parent file based on props if child1 is rendered or not.
你不应该检查你的子组件是否被渲染,而是检查实际渲染的内容(测试库鼓励你这样做)
为了在 react-testing-library 中测试它,你可以这样做:
test("If Child1 is rendered!", () => {
const { getByText } = render(<Parent number="one" word="hello" />);
expect(getByText("I am Child1")).toBeInTheDocument();
});
我正在尝试在 React 中学习 tdd。我有一个父组件,它从应用程序组件获取道具,并根据道具渲染 child1 组件或 child2 组件。这是我的反应文件:
App.js
import './App.css';
import Parent from './Parent';
function App() {
return (
<div className="App">
<Parent number={"one"} word={"hello"}/>
{/* can be one or two */}
</div>
);
}
export default App;
Parent.js
import React from 'react';
import Child1 from './Child1';
import Child2 from './Child2';
function Parent({number,word}) {
return (
<div className="Parent" data-testid="parent-test">
{number === 'one' &&
<Child1 />
}
{number === 'two' &&
<Child2/>
}
</div>
);
}
export default Parent;
child1.js
import React from 'react';
function Child1() {
return (
<div>
I am Child1
</div>
);
}
export default Child1;
child2.js
import React from 'react';
function Child2() {
return (
<div>
I am Child2
</div>
);
}
export default Child2;
`
How can I write a test using Jest and enzyme to check in parent file based on props if child1 is rendered or not.
你不应该检查你的子组件是否被渲染,而是检查实际渲染的内容(测试库鼓励你这样做)
为了在 react-testing-library 中测试它,你可以这样做:
test("If Child1 is rendered!", () => {
const { getByText } = render(<Parent number="one" word="hello" />);
expect(getByText("I am Child1")).toBeInTheDocument();
});