Awaiting after setProps with Enzyme



下面我试图使用Component.setProps进行测试,我如何等待useEffectsetProps之后在<MeowComponent>中运行?

const history = createMemoryHistory();
history.push('/3');
const fetch = jest.fn()
const Component = mount(
<Router history={history}>
<Route path="/meow/:number">
<MeowComponent fetch={fetch} />
</Route>
</Router>
);
// This is the use case where component initially mounts
expect(fetch).toHaveBeenNthCalledWith(1, '3', false, false);
Component.setProps({ number: '2' });
// this fails because we haven't awaited the changes..
expect(fetch).toHaveBeenNthCalledWith(2, '2', false, false);

尝试:

import { mount } from 'enzyme';
import { createMemoryHistory } from 'history';
import React, { useEffect } from 'react';
import { Route, Router, useParams } from 'react-router-dom';
function flushPromises() {
return new Promise((resolve) => setTimeout(resolve, 0));
}
const MeowComponent = ({ fetch }) => {
const { number } = useParams<{ number: string }>();
console.log('number', number);
useEffect(() => {
fetch(number, false, false);
}, [number]);
return null;
};
describe('72495434', () => {
test('should pass', async () => {
const fetch = jest.fn();
const history = createMemoryHistory();
history.push('/meow/3');
mount(
<Router history={history}>
<Route path="/meow/:number">
<MeowComponent fetch={fetch} />
</Route>
</Router>
);
expect(fetch).toHaveBeenNthCalledWith(1, '3', false, false);
history.push('/meow/2');
await flushPromises();
expect(fetch).toHaveBeenNthCalledWith(2, '2', false, false);
});
});

测试结果:

PASS  stackoverflow/72495434/index.test.tsx (10.054 s)
72495434
✓ should pass (62 ms)
console.log
number 3
at MeowComponent (stackoverflow/72495434/index.test.tsx:12:11)
console.log
number 2
at MeowComponent (stackoverflow/72495434/index.test.tsx:12:11)
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.512 s, estimated 11 s

最新更新