我正在使用React TestUtil.renderIntoDocument
来测试React组件类,就像这样(只使用TypeScript而不是Babel):
describe("MyComponent", () => { it("will test something after being mounted", () => { var component = TestUtils.renderIntoDocument(); // 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 () } } // 2. shallow-render and test componentDidMount const wrapper = shallow( ) 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) })
Step1: Use "jest.spyOn" on "componentWillUnmount" method. Step2: Trigger unmount on the mounted component. Finally: check if componentWillUnmount is called when component is unmounted
码
it('componentWillUnmount should be called on unmount', () => { const component = createComponent(); const componentWillUnmount = jest.spyOn(component.instance(), 'componentWillUnmount'); component.unmount(); expect(componentWillUnmount).toHaveBeenCalled(); });
没错,但是TestUtils.renderIntoDocument
返回一个ReactComponent,可以访问组件的生命周期方法。
因此,您可以手动致电component.componentWillUnmount()
。