React - 当 Jest 和 Enzyme 状态改变时,测试组件中条件渲染的元素是否被渲染

时间:2021-06-03 16:02:30

标签: reactjs typescript testing jestjs enzyme

我的组件中有一个 ReactElement,如果设置了 state 属性,它就会呈现。现在我想通过在我的测试中设置状态来测试该行为,并检查该元素是否已在之后呈现。如果我通过在安装的包装器上使用 setState({key: object}) 更新状态,尽管包装器的状态已更新,但它似乎对我的组件没有影响。我是不是在错误的地方进行状态更新?

MyComponent.tsx

class MyCompoonent extends React.Component {
    ...
    render() {
        ....
        // Render <div> if state is set
        {this.state.myObject && (<div>Test me</div>)}
    }
}

MyTest.tsx

...
it('should render div if state is set', () => {
    
    // Create fake object
    const fakeObject: FakeObjectType = { name: "fake" }; 
    
    // Mount component
    const wrapper = mount(<Component />);
   
    // Update state
    wrapper.setState({
        myObject: fakeObject
    }, () => {
        
        // Prints fakeObject as part of state
        console.log(wrapper.state());

        // I don´t think I need that?!
        wrapper.update();
        
        // Wrapper has not been rerendered,
        // <div> is still not part of the printed output
        console.log(wrapper.debug());

        // Test failes ;(
        expect(wrapper.containsMatchingElement(<div>Test me</div>)).toBeTruthy();
    }
});

0 个答案:

没有答案