如何使用jest和酶正确测试反应功能组件?

时间:2021-06-08 09:39:26

标签: reactjs unit-testing jestjs enzyme

my-component.js

import axios from "axios";
import React from "react";

const UnitTest = () => {
  const [todo, set_todo] = React.useState({});

  React.useState(() => {
    const onMounted = async () => {
      const getTodo = await axios.get("https://jsonplaceholder.typicode.com/todos/1");
      set_todo(getTodo.data);
    };
    onMounted();
  }, []);

  return (
    <div id="UnitTest">
      <p>{todo.title}</p>
    </div>
  );
};

export default UnitTest;

api 响应

{
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
}

my-component.test.js

import { mount } from "enzyme";

import UnitTest from "../../src/pages/unit-test";

describe("UnitTest component", () => {
  let wrapper = mount(<UnitTest />);

  it("should render the component", () => {
    wrapper = mount(<UnitTest />);
    console.log(wrapper.debug());
    expect(wrapper.find("p").text()).toEqual("delectus aut autem");
  });
});

测试结果

enter image description here

如何在 console.log(wrapper.debug()) 时让我的 <p> 标签包含 delectus aut autem,如果我想更新状态 (set_todo) 是否有可能

{
    "userId": 2,
    "id": 3,
    "title": "second title",
    "completed": true
}

从我的测试文件和更新断言变成 expect(wrapper.find("p").text()).toEqual("second titile"); ?

1 个答案:

答案 0 :(得分:0)

使用 jest.spyOn(object, methodName) 方法为 axios.get() 方法及其解析值创建模拟。

使用 act()promisesetTimeout 一起创建宏任务,以等待 axios.get() 钩子中创建的 useEffect 方法的承诺被解析。

例如

MyComponent.jsx

import axios from 'axios';
import React from 'react';

const UnitTest = () => {
  const [todo, set_todo] = React.useState({});

  React.useEffect(() => {
    const onMounted = async () => {
      const getTodo = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
      set_todo(getTodo.data);
    };
    onMounted();
  }, []);

  return (
    <div id="UnitTest">
      <p>{todo.title}</p>
    </div>
  );
};

export default UnitTest;

MyComponent.test.jsx

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

const whenStable = async () => {
  await act(async () => {
    await new Promise((resolve) => setTimeout(resolve, 0));
  });
};

describe('67885144', () => {
  it('should pass', async () => {
    const axiosGetSpy = jest.spyOn(axios, 'get').mockResolvedValueOnce({ data: { title: 'delectus aut autem' } });
    const wrapper = mount(<UnitTest />);
    await whenStable();

    expect(wrapper.find('p').text()).toEqual('delectus aut autem');
    expect(axiosGetSpy).toBeCalledWith('https://jsonplaceholder.typicode.com/todos/1');
    axiosGetSpy.mockRestore();
  });
});

测试结果:

 PASS  examples/67885144/MyComponent.test.jsx (7.902 s)
  67885144
    ✓ should pass (45 ms)

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