我正在使用 React 的 TestUtil.renderIntoDocument
来测试 React 组件类,like this (只有我使用 TypeScript 而不是 Babel):
describe("MyComponent", () => {
it("will test something after being mounted", () => {
var component = TestUtils.renderIntoDocument(<MyComponent />);
// some test...
})
})
这可行,但我想编写一个测试来验证 componentWillUnmount
的行为是否符合预期。然而,测试运行程序似乎从未卸载该组件,这并不奇怪。所以我的问题是:如何从测试中卸载组件? TestUtil
没有任何看起来像我想要的东西,类似于我想象的 removeFromDocument
的东西。
最佳答案
使用enzyme 3
库的shallow()
和unmount()
,您可以测试生命周期方法是否已被调用,如下所示:
it(`lifecycle method should have been called`, () => {
const componentDidMount = jest.fn()
const componentWillUnmount = jest.fn()
// 1. First extends your class to mock lifecycle methods
class Foo extends MyComponent {
constructor(props) {
super(props)
this.componentDidMount = componentDidMount
this.componentWillUnmount = componentWillUnmount
}
render() {
return (<MyComponent />)
}
}
// 2. shallow-render and test componentDidMount
const wrapper = shallow(<Foo />)
expect(componentDidMount.mock.calls.length).toBe(1)
expect(componentWillUnmount.mock.calls.length).toBe(0)
// 3. unmount and test componentWillUnmount
wrapper.unmount()
expect(componentDidMount.mock.calls.length).toBe(1)
expect(componentWillUnmount.mock.calls.length).toBe(1)
})
关于reactjs - 使用 Jest 测试 React componentWillUnmount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113100/