code:
class Foo extends React.PureComponent<undefined,undefined>{
bar:number;
async componentDidMount() {
this.bar = 0;
let echarts = await import('echarts'); // async import
this.bar = 100;
}
}
test:
describe('...', () => {
test('...', async () => {
const wrapper = shallow(<Foo/>);
const instance = await wrapper.instance();
expect(instance.bar).toBe(100);
});
});
Error:
Expected value to be:
100
Received:
0
There are many React testing libraries on the market, but two of the most popular are React Testing Library (RTL) and Enzyme. Both of them are used for testing react components, and both provide the tools needed for testing some application, but they have two different approaches.
Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.
Solution:
1: use the async/await syntax.
2: Use mount (no shallow).
3: await async componentLifecycle.
For ex:
test(' ',async () => {
const wrapper = mount(
<Foo />
);
await wrapper.instance().componentDidMount();
})
Something like this should work for you:-
describe('...', () => {
test('...', async () => {
const wrapper = await mount(<Foo/>);
expect(wrapper.instance().bar).toBe(100);
});
});
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