测试restapi是否在玩笑中有用

问题描述 投票:0回答:1

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

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

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

reactjs jestjs react-hooks fetch-api
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.