在我的測試中,我想阻止我的主線程,直到我的某個組件完成其整個生命週期方法(通過componentDidUpdate()
,完成後我觸發導致其添加子組件的事件自己。我該怎麼做?等待React組件完成更新
事情是這樣的:
describe('my <Component />',() => {
it('should do what I want when its button is clicked twice',() => {
const wrapper = mount(<Component />);
const button = wrapper.find('button');
// This next line has some side effects that cause <Component /> to add
// some children components to itself...
button.simulate('click', mockEvent);
// ... so I want to wait for those children to completely go through
// their lifecycle methods ...
wrapper.instance().askReactToBlockUntilTheComponentIsFinishedUpdating();
// ... so that I can be sure React is in the state I want it to be in
// when I further manipulate the <Component />
button.simulate('click', mockEvent);
expect(whatIWant()).to.be.true;
});
});
(我想這樣做,因爲,現在,我得到這樣的警告:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.
我相信我得到它,因爲我的測試引起我的組件比React的內部多線程魔術更快地改變其內部狀態,因此,當我第二次運行button.simulate('click')
時,React已經實例化了新的子組件,但還沒有完成它們的安裝。 React完成更新荷蘭國際集團我的組件及其子是解決這個問題的最好辦法)
是什麼單擊處理呢?所有的狀態改變應該是同步的,除非你特別有一些定時器/異步的東西正在進行。 – Jacob
DOM更新也是同步的,除非你做了一些奇怪的事情或者使用了React的異國情調。如果你的'setState'警告是因爲你的組件本身在mount之前做了'setState',我不會感到驚訝。 – Jacob
@Jacob我正在使用第三方庫[React Widgets](https://jquense.github.io/react-widgets/docs/)。我的' '有一個React Widgets'DateTimePicker'作爲它的一個孩子,並且警告似乎是從'DateTimePicker'內發出的。所以不幸的是,我確切地知道我的事件會導致什麼變化,我很容易無法嘗試查看組件,以確保它不會行爲不端。 –
Kevin