首页 > 解决方案 > 使用钩子测试有状态的 React 组件时出现意外结果?(笑话)

问题描述

我是测试新手,创建具有计数器状态和 useState 反应钩子的简单组件,当单击按钮时增加计数器:

零件:

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 correctly', () => {
    let wrapper = shallow(<Counter/>);
    const counter  = wrapper.find('h2');
    const button = wrapper.find('button');
    button.simulate('click')
    console.log(counter.text()) // 0
})

counter.text()模拟按钮单击打印0而不是1后记录;当我试图监视 useState 时,我遇到了同样的问题:

it('increment counter correctlry', () => {
    let wrapper = shallow(<Card />);
    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

我究竟做错了什么??

标签: javascriptreactjstestingjestjsenzyme

解决方案


enzymev3 中,您应该在触发点击处理程序后重新找到h2浅层包装器。然后您将获得新的h2浅包装器引用,其中包含counter. 查看migration-from-2-to-3.html#calling-props-after-a-state-change了解更多信息。

例如

Counter.jsx

import React, { useState } from 'react';

export 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.text.jsx

import { shallow } from 'enzyme';
import React from 'react';
import { Counter } from './Counter';

describe('64148085', () => {
  it('increment counter correctly', () => {
    const wrapper = shallow(<Counter />);
    const button = wrapper.find('button');
    button.simulate('click');
    expect(wrapper.find('h2').text()).toBe('1');
  });
});

带有覆盖率报告的单元测试结果

 PASS  src/stackoverflow/64148085/Counter.test.tsx
  64148085
    ✓ increment counter correctly (12ms)

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |      100 |      100 |      100 |      100 |                   |
 counter.tsx |      100 |      100 |      100 |      100 |                   |
-------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.472s, estimated 12s

推荐阅读