使用自定义api挂钩时获取“ arr [Symbol.iterator]不是函数”

时间:2019-09-12 12:00:18

标签: javascript reactjs unit-testing jestjs react-hooks

我编写了一个自定义钩子,该钩子使api调用返回结果和错误(如果存在)。当尝试对使用自定义钩子的组件进行Jest测试时,在钩子出现之前,我得到“ arr [Symbol.iterator]不是函数”或“无法读取未定义的属性'Symbol(Symbol.iterator)'”使用笑话shallow()

我觉得这是api响应与诺言一起工作的问题,因此我尝试围绕.then或“ wait”进行aysnc的各种不同方法。这不能解决问题

我的自定义api钩子

/* Packages */
import { useEffect, useState } from 'react';

export const useApiCall = (endPoint) => {
    const [hasError, setHasErrors] = useState(false);
    const [fetchData, setFetchData] = useState(null);

    const getData = async () => {
        try {
            const response = await fetch(endPoint);

            if (!response.ok) {
                throw Error(response.statusText);
            }

            const responseJSON = await response.json();

            setFetchData(responseJSON.data);
        }
        catch (error) {
            setHasErrors(true);
        }
    }

    useEffect(() => {
        getData()
    },[])

    return [fetchData, hasError]
}

我使用钩子的组件

/* Packages */
import React, { useState } from 'react';

/* Utils */
import { useApiCall } from '../../utils/useApiCall';

/* Components */
import FooterStructure from './FooterStructure'

const Footer = () => {
    const [footerLinks, error] = useApiCall('http://www.mocky.io/v2/5d7678f93200000362297bae');
    const [visible, setVisible] = useState();

    const showContent = () => {
        setVisible(!visible);
    }

    const componentProps = {
        footerLinks : footerLinks,
        error : error,
        visible : visible,
        showContent : showContent
    };

    return (
        <FooterStructure {...componentProps} />
    )
};

export default Footer;

我的Jest测试没有/有承诺

import { shallow, mount } from 'enzyme';
import Footer from '.';
import mock from './__mocks__/FooterLinks';
import { useApiCall } from '../../utils/useApiCall';
import { testHook } from '../../utils/TestUtils';

jest.mock('../../utils/useApiCall');

let footerData,
    wrapper;

beforeEach(() => {
    wrapper = shallow(<Footer />);

    testHook(async () => {
        useApiCall.mockImplementation(() => Promise.resolve({ data: mock }));
        useApiCall().then((resolve)=>{
            footerData = resolve;
        })
        // This promise gives the same error
        // .then(()=>{
        //     wrapper = shallow(<Footer />);
        // })
        // .catch((error)=>{
        //     console.log(error);
        // });
    });
});

describe('Footer links', () => {
    it('should have 3 links', () => {
        expect(footerData.data.length).toEqual(3);
    });
});

错误

  Footer links
    ✕ should have 3 links (46ms)

  ● Footer links › should have 3 links

    TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined

       8 | import FooterStructure from './FooterStructure'
       9 | 
    > 10 | const Footer = () => {
         |                      ^
      11 |     const [footerLinks, error] = useApiCall('http://www.mocky.io/v2/5d7678f93200000362297bae');
      12 |     const [visible, setVisible] = useState();
      13 | 

      at _iterableToArrayLimit (node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js:8:22)
      at _slicedToArray (node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/slicedToArray.js:8:33)
      at Footer (src/global/Footer/index.js:10:22)
      at ReactShallowRenderer.render (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:794:32)
      at render (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:636:55)
      at fn (node_modules/enzyme-adapter-utils/src/Utils.js:99:18)
      at Object.render (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:636:20)
      at new render (node_modules/enzyme/src/ShallowWrapper.js:397:22)
      at shallow (node_modules/enzyme/src/shallow.js:10:10)
      at Object.<anonymous>.beforeEach (src/global/Footer/Footer.test.js:14:15)

  ● Footer links › should have 3 links

    TypeError: Cannot read property 'data' of undefined

      24 | describe('Footer links', () => {
      25 |     it('should have 3 links', () => {
    > 26 |         expect(footerData.data.length).toEqual(3);
         |                           ^
      27 |     });
      28 | });
      29 | 

      at Object.data (src/global/Footer/Footer.test.js:26:27)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.66s, estimated 1s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.```

My jest test with promise

0 个答案:

没有答案