开玩笑的模拟错误-TypeError:无法读取未定义的属性“组”

时间:2019-12-03 22:49:40

标签: javascript reactjs unit-testing jestjs enzyme

我有一个组件调用名为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)

0 个答案:

没有答案