测试restapi内的useeffect

时间:2019-12-17 06:12:59

标签: reactjs jestjs react-hooks fetch-api

我是Jest的新手,我正在为以下功能编写测试用例,

useEffect(() => {
    fetch("http://ip-api.com/json")
      .then(res => res.json())
      .then(data => {
        cntCode = `country_code=${data.countryCode}`;
        country = `country=${data.country}`;
      });
  });

我尝试了几种方法来涵盖使用,但是我不知道如何涵盖此功能。有人可以帮我编写测试用例吗?

1 个答案:

答案 0 :(得分:0)

这是单元测试解决方案:

index.tsx

import React, { useEffect, useState } from 'react';

export const MyComponent = () => {
  const [cntCode, setCntCode] = useState('');
  const [country, setCountry] = useState('');

  useEffect(() => {
    fetch('http://ip-api.com/json')
      .then((res) => res.json())
      .then((data) => {
        setCntCode(data.countryCode);
        setCountry(data.country);
      });
  }, [cntCode, country]);

  return (
    <div>
      country: {country}, cntCode: {cntCode}
    </div>
  );
};

index.test.ts

import { MyComponent } from './';
import React from 'react';
import { mount } from 'enzyme';
import { act } from 'react-dom/test-utils';

describe('MyComponent', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });
  it('should pass', async () => {
    const mResponse = jest.fn().mockResolvedValue({ countryCode: 123, country: 'US' });
    (global as any).fetch = jest.fn(() => {
      return Promise.resolve({ json: mResponse });
    });
    const wrapper = mount(<MyComponent></MyComponent>);
    expect(wrapper.exists()).toBeTruthy();
    expect(wrapper.text()).toBe('country: , cntCode: ');
    await act(async () => {
      await new Promise((resolve) => setTimeout(resolve, 0));
    });
    expect(wrapper.text()).toBe('country: US, cntCode: 123');
    expect((global as any).fetch).toBeCalledWith('http://ip-api.com/json');
  });
});

覆盖率100%的单元测试结果:

 PASS  src/stackoverflow/59368499/index.test.tsx (9.629s)
  MyComponent
    ✓ should pass (73ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.64s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59368499