使用 Jest 和 Context 测试执行

Test execution with Jest and Context

我想对执行名为 deleteEmployee() 的函数的按钮进行测试,但我遇到的问题是,当我执行测试时,出现以下错误。

错误

  ● Employees Component › should execute deleteEmployee (it has interacion with context) when click button

    TypeError: Cannot destructure property 'employees' of '((cov_2ati4da0re(...).s[3]++) , (0 , _react.useContext)(...))' as it is undefined.

       6 |     const navigate = useNavigate();
       7 |     const params = useParams();
    >  8 |     const {employees, setEmployees} = useContext(EmployeesContext);
         |            ^
       9 |
      10 |     const deleteEmployee = (id) => {
      11 |         setEmployees(employees.filter(({dni}) => dni !== id))

函数

const deleteEmployee = (id) => {
        setEmployees(employees.filter(({dni}) => dni !== id))
}

测试

  it("should execute delete employee function when click button", () => {
    const wrapper = mount(
      <EmployeesContext.Provider>
        <Employees />
      </EmployeesContext.Provider>
    );
    const button = wrapper.find("button").first();
    button.simulate("click");
    expect(button.props().onClick).toBeDefined();
  });

在我的上下文中,我只定义了一个基本代码和一个带有一些默认值的初始定义。

上下文声明

import React, { useState } from 'react';
import { Header } from './components/Header';
import { EmployeesContext } from './context/EmployeesContext';
import { AppRouter } from './router/AppRouter';
import { BrowserRouter as Router} from 'react-router-dom'

function App() {
  const [employees, setEmployees] = useState([
    {
      name: "Jaime Armando Straus",
      address: "Los Angeles, CA",
      dni: "MBJ34368V12P5",
      birth: "19/03/1998",
      phone: "5628903455",
      email: "jaime.armando@aspiresys.com",
      position: "Front-end Developer"
    },
    {
      name: "Jose Armando Straus",
      address: "Washington, DC",
      dni: "NFIN3543543NKBN",
      birth: "19/03/1980",
      phone: "5628903455",
      email: "jose.armando@aspiresys.com",
      position: "Back-end Developer"
    }
  ]);

  return (
    <EmployeesContext.Provider value={{employees, setEmployees}}>
      <Router>
        <div className="app">
          <Header />
          <AppRouter />
        </div>
      </Router>
    </EmployeesContext.Provider>
  );
}

export default App;

上下文代码

import { createContext } from "react";

export const EmployeesContext = createContext(null);

您需要在测试中向提供者提供 value,如下所示:

it("should execute delete employee function when click button", () => {
  const mockEmployees = [];
  const mockSetEmployees = jest.fn();
  const wrapper = mount(
    <EmployeesContext.Provider value={{ mockEmployees, mockSetEmployees }}>
      <Employees />
    </EmployeesContext.Provider>
  );
  const button = wrapper.find("button").first();
  button.simulate("click");
  expect(button.props().onClick).toBeDefined();
});