我正在使用React TestUtil.renderIntoDocument来测试React组件类,就像这样(只使用TypeScript而不是Babel):
describe("MyComponent", () => {
it("will test something after being mounted", () => {
var component = TestUtils.renderIntoDocument(<MyComponent />);
// some test...
})
})
Run Code Online (Sandbox Code Playgroud)
这有效,但我想编写一个测试,验证其componentWillUnmount行为符合预期.但是,似乎测试运行器从未卸载组件,这并不奇怪.所以我的问题是:如何在测试中卸载组件?该TestUtil不会有什么看起来像什么,我想,沿着线的东西removeFromDocument我会想象.
bob*_*bob 16
使用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)
})
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)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();
});
Run Code Online (Sandbox Code Playgroud)
没错,但是TestUtils.renderIntoDocument返回一个ReactComponent,可以访问组件的生命周期方法。
因此,您可以手动致电component.componentWillUnmount()。
| 归档时间: |
|
| 查看次数: |
13325 次 |
| 最近记录: |