测试restapi内的useeffect玩笑 [英] test restapi inside useeffect in jest

查看:87
本文介绍了测试restapi内的useeffect玩笑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Jest and I'm writing test case for the below function,

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

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

I tried few ways to cover using but I'm not able to figure out how to cover this function. Can someone help me in writing the testcase for this please?

推荐答案

这是单元测试解决方案:

Here is the unit test solution:

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%:

Unit test result with 100% coverage:

 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

这篇关于测试restapi内的useeffect玩笑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆