gpt4 book ai didi

javascript - 使用 enzyme : how to wait for setState within component's method to finish before proceeding with test case 的 JS 单元测试

转载 作者:行者123 更新时间:2023-11-29 15:57:36 25 4
gpt4 key购买 nike

我有一个组件 MyComponent,其方法 doSomething 更新状态,renderChildren 根据这些状态呈现子组件:

class MyComponent extends Component {
constructor(props) {
super(props);
...
this.state = {
renderChildA: true,
renderChildB: false,
};
}

doSomething = (params) => {
// Do something...

this.setState({
renderChildA: false,
renderChildB: true,
});
}

renderChildren = () => {
const { renderChildA, renderChildB } = this.state;
if (renderChildA) {
return <ChildComponentA />;
} else if (renderChildB) {
return <ChildComponentB />;
}
}

render() {
return (
<div>
{this.renderChildren()}
...
</div>
);
}
}

注意:该组件也连接到 Redux,但已被简化。

对于单元测试,我正在调用 doSomething 并验证 ChildComponentB 是否可见:

test('doSomething should trigger ChildComponentB to pop up', () => {
const wrapper = shallow(
<MyComponent
...
/>,
).dive();

wrapper.instane().doSomething(params); // assume params is defined

const childComponentB = wrapper.find('ChildComponentB');
expect(childComponentB).toHaveLength(1);
});

然而,上面的测试用例失败了:

my-component.test.jsx > Some test group name > doSomething should trigger ChildComponentB to pop up

expect(received).toHaveLength(length)

Expected value to have length:
1
Received:
// Some giant JSON object
recevied.length:
0

xxx | const childComponentB = wrapper.find('ChildComponentB');
xxx | expect(childComponentB).toHaveLength(1);
xxx | });

根据日志记录,我发现 doSomething 中的 setState 是在测试用例中的 expect 语句之后触发的。我怀疑这是自 setState is asynchronous 以来发生的,但我不知道解决方法(setTimeout 除外)。

最佳答案

您可以尝试手动更新组件以获取最新状态:

  wrapper.instance().doSomething(params); // assume params is defined
wrapper.update();
const childComponentB = container.find('ChildComponentB');
expect(childComponentB).toHaveLength(1);

更多信息:https://airbnb.io/enzyme/docs/api/ShallowWrapper/update.html

关于javascript - 使用 enzyme : how to wait for setState within component's method to finish before proceeding with test case 的 JS 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57280880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com