簡體   English   中英

使用鈎子測試有狀態的 React 組件時出現意外結果? (笑話)

[英]Unexpected results in testing a stateful React component with hooks?? (Jest)

我是測試新手,創建具有計數器狀態和 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>
    )
}

計數器.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

我究竟做錯了什么??

enzyme v3 中,您應該在觸發點擊處理程序后重新找到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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM