I have the following code in a jest based test:
it('will show the hero loop if there is one', function() {
var React = require('react/addons');
var ShowsDetailHeader = require('../../../../routes/shows/components/ShowsDetailHeader.jsx');
var mockData = require('../../../../mock/episodeDetailData');
mockData.data.show.assets._webHeroVideoUrl = 'https://test.video.com';
var Subject = require('../../../../mock/stubRouterContext')(ShowsDetailHeader, {
show: mockData.data.show
});
var TestUtils = React.addons.TestUtils;
var showsHeader = TestUtils.renderIntoDocument(
<Subject />
);
showsHeader.setState({
showVideo: true
});
var videoClass = TestUtils.findRenderedDOMComponentWithClass(showsHeader, 'flex-video').getDOMNode().getAttribute('class');
expect(videoClass.indexOf('in')).toBe(-1);
console.log(videoClass);
});
My previous test tests the initial state of the component. I now want to call setState to check the component after a state change. The videoClass i'm logging here stays the same. I am on react 0.12. and latest jest 0.4.0.
Any ideas on how to test what happens after set state?
If React fails to do re-render components automatically, it's likely that an underlying issue in your project is preventing the components from updating correctly.
setState() will always lead to a re-render unless shouldComponentUpdate() returns false . To avoid unnecessary renders, calling setState() only when the new state differs from the previous state makes sense and can avoid calling setState() in an infinite loop within certain lifecycle methods like componentDidUpdate .
State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass.
The render() function should be pure, meaning that it does not modify a component's state. It returns the same result each time it's invoked, and it does not directly interact with the browser. In this case, avoid using setState() here.
setState
is async, so you probably need
showsHeader.setState({
showVideo: true
});
jest.runAllTicks();
find ...
expect ...
But I think state should be private and shouldn't be direct changed, state should be change inside a component, cause by ui event or data change.
an option is usingprops
for public, if you wanna change the component from outside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With