我是Jest/React初学者。在jest的it
我需要等到所有的承诺已经执行之前,实际检查。如何对提取完成后呈现的React组件进行单元测试?
我的代码是与此类似:
export class MyComponent extends Component {
constructor(props) {
super(props);
this.state = { /* Some state */ };
}
componentDidMount() {
fetch(some_url)
.then(response => response.json())
.then(json => this.setState(some_state);
}
render() {
// Do some rendering based on the state
}
}
当组件被安装时,render()
运行两次:构造运行后一次,并且之后一旦fetch()
(在componentDidMount()
)饰面和链接的承诺完成执行) 。
我的测试代码是与此类似:
describe('MyComponent',() => {
fetchMock.get('*', some_response);
it('renders something',() => {
let wrapper = mount(<MyComponent />);
expect(wrapper.find(...)).to.have.something();
};
}
无论我从it
返回,在第一次运行后render()
执行,但第二次了。例如,如果我返回fetchMock.flush().then(() => expect(...))
,则在第二次致电render()
(我相信我能理解为什么)之前执行返回的承诺。
我该如何等待,直到第二次render()
在运行之前调用expect()
?
这听起来像你想在一次测试中测试太多东西。你想要测试的是当组件装入时调用你的读取函数,然后你有多个其他测试显式地传递给它们,你可以检查组件是否被正确渲染。 –
@MattWatson如果我检查(1)fetch函数被调用,并且(2)传递状态正确渲染,那么我没有检查(1.5)状态是否设置正确。我将如何检查状态设置是否正确? –