如何在玩笑中模拟/监视 useState 钩子?

IT技术 javascript reactjs testing jestjs enzyme
2021-05-02 14:17:30

我试图监视 useState React 钩子,但我总是测试失败

这是我的 React 组件:

const Counter= () => {
    const[counter, setCounter] = useState(0);

    const handleClick=() => {
        setCounter(counter + 1);
    }

    return (
        <div>
            <h2>{counter}</h2>
            <button onClick={handleClick} id="button">increment</button>
        </div>
    )
}

counter.test.js :

it('increment counter correctlry', () => {
    let wrapper = shallow(<Counter/>);
    const setState = jest.fn();
    const useStateSpy = jest.spyOn(React, 'useState');

    useStateSpy.mockImplementation((init) => [init, setState]);
     const button = wrapper.find("button")
     button.simulate('click');
     expect(setState).toHaveBeenCalledWith(1);
})

不幸的是,这不起作用,我得到该消息的测试失败:

expected 1
Number of calls: 0
4个回答

您需要使用React.useState而不是单个 import useState

我认为是关于代码如何转换的,正如您在 babel repl 中看到的那样,useState从单个导入最终与module导入之一不同

_react.useState // useState
_react.default.useState // React.useState;

所以你监视_react.default.useState但你的组件使用_react.useState. 监视单个导入似乎是不可能的,因为您需要该函数属于一个对象,这里有一个非常广泛的指南,解释了模拟/监视module的方法https://github.com/HugoDF/mock-spy-module-进口

正如@Alex Mackay 提到的,你可能想改变你对测试 React 组件的心态,建议转向 react-testing-library,但如果你真的需要坚持使用酶,你不需要走那么远去模拟react库本身

dieu 的回答让我找到了正确的方向,我想出了这个解决方案:

  1. 模拟使用状态从 react 返回 jest.fn() 作为 useState:1.1 之后也立即导入 useState - 现在将是 e jest 模拟(从 jest.fn() 调用返回)

jest.mock('react', ()=>({
  ...jest.requireActual('react'),
  useState: jest.fn()
}))
import { useState } from 'react';

  1. 稍后在 beforeEach 中,将其设置为原始 useState,对于所有需要它不被嘲笑的情况

describe("Test", ()=>{
  beforeEach(()=>{
    useState.mockImplementation(jest.requireActual('react').useState);
    //other preperations
  })
  //tests
})

  1. 在测试本身中根据需要模拟它:

it("Actual test", ()=>{
  useState.mockImplementation(()=>["someMockedValue", someMockOrSpySetter])
})

离别笔记:虽然在“黑匣子”是单元测试中弄脏你的手在概念上可能有些错误,但有时这样做确实非常有用。

恼人的是 Codesandbox 目前在其测试module上遇到问题,所以我无法发布一个工作示例,但我会尝试解释为什么模拟useState通常是一件坏事。

用户不关心是否useState已被调用,他们关心当我单击 increment 计数应该增加 1 时,这就是您应该测试的内容。

// App
import React, { useState } from "react";
export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
    </div>
  );
}
// Tests
import React from "react";
import App from "./App";
import { screen, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

describe("App should", () => {
  it('increment count value when "Increment" btn clicked', () => {
    // Render the App
    render(<App />);
    // Get the count in the same way the user would, by looking for 'Count'
    let count = screen.getByText(/count:/);
    // As long as the h1 element contains a '0' this test will pass
    expect(count).toContain(0);
    // Once again get the button in the same the user would, by the 'Increment'
    const button = screen.getByText(/increment/);
    // Simulate the click event
    userEvent.click(button);
    // Refetch the count
    count = screen.getByText(/count:/);
    // The 'Count' should no longer contain a '0'
    expect(count).not.toContain(0);
    // The 'Count' should contain a '1'
    expect(count).toContain(1);
  });
  // And so on...
  it('reset count value when "Reset" btn is clicked', () => {});
  it('decrement count value when "Decrement" btn is clicked', () => {});
});

@testing-library如果您对这种测试方式感兴趣,请务必检查一下我从enzyme大约 2 年前切换过来,从那以后就再也没碰过它。

只需要在测试文件中导入 React,例如:

import * as React from 'react';

之后,您可以使用模拟功能。

import * as React from 'react';

:
:
it('increment counter correctlry', () => {
    let wrapper = shallow(<Counter/>);
    const setState = jest.fn();
    const useStateSpy = jest.spyOn(React, 'useState');

    useStateSpy.mockImplementation((init) => [init, setState]);
     const button = wrapper.find("button")
     button.simulate('click');
     expect(setState).toHaveBeenCalledWith(1);
})