我有一个组件调用名为getGroups
client / src / apis / getGroups.js
export default const getGroups = async () =>{
let data = await fetch("/groups");
return await data.json();
}
client / __ mocks __ / getGroups.js
const fakeResponse = {groups: [{},{}]}
export const getGroups = async () => return await Promise.resolve(fakeData)
MyComponent包含一个useEffect:
export default function MyWidget({
groupId,
}) {
// Store group object in state
const [group, setGroup] = useState(null);
// Retrive groups on load
useEffect(() => {
if (groupId && group === null) {
const runEffect = async () => {
const { groups } = await getGroups();
const groupData = groups.find(
g => g.name === groupId || g.id === Number(groupId)
);
setGroup(groupData);
};
runEffect();
}
}, [group, groupId]);
const params =
group && `&id=${group.id}&name=${group.name}`;
const src = `https://mylink.com?${params ? params : ''}`;
return (
<iframe src={src}></iframe>
);
}
我想测试组件是否使用正确的src url呈现,该URL由模拟的getGroups
调用确定:
jest.mock('../../apis/getGroups');
describe('<MyWidget /> with api handling', () => {
it('renders src with api params', async done => {
// the effect will get called
// the effect will call getGroups
// the iframe will contain group parameters for the given groupId
let component;
act(async () => {
component = mount(
<UsageWidget surface={`${USAGE_SURFACES.metrics}`} groupId={'2'} />
);
});
setTimeout(() => {
expect(component.find('iframe').prop('src')).toContain('SPAM');
done();
});
});
});
错误:
TypeError: Cannot read property 'groups' of undefined
29 | if (groupId && group === null) {
30 | const runEffect = async () => {
> 31 | const { groups } = await getGroups();
32 | const groupData = groups.find(
33 | g => g.name === groupId || group.id === Number(groupId)
34 | );
at runEffect (src/utils/MyWidget.jsx:31:58)