测试useEffect卸载回调,使用酶中的行为调用

问题描述 投票:2回答:1

我有这种设置的组件

const ChestWithToys = ({toyBoxId, handleTidyToys})=> {
    /* do stuff with toys */
    useEffect(() => () => handleTidyToys(), [toyBoxId])
}

这是我的酶和作用测试(来自react-dom/test-utils

it('tidies toys on unmount', () => {
    let handleTidyToys = sinon.stub();
    let wrapper = shallow(<ChestWithToys toyBoxId={1} handleTidyToys={handleTidyToys} />);
    expect(handleTidyToys).to.have.callCount(0);
    act(() => {
       wrapper.unmount();
    });
    expect(handleTidyToys).to.have.callCount(1);
});

该组件功能正常。但是在测试中,永远不会调用handleTidyToys。是什么赋予了?我找不到在其中进行卸载的更好的example,但是从我看到的那可以触发我的清理回调。

如果我用setProps替换卸载并更改queryId,它仍然不会触发。

酶不兼容,还是我犯了其他错误?

编辑:我刚刚将一堆console.logs放到useEffect中,并且围绕它,它根本没有运行。

javascript reactjs enzyme react-hooks react-dom
1个回答
1
投票

[这是一种对我有用的方法,但有一些警告:

  1. 我用jest代替了sinon进行间谍和嘲笑;
  2. 我使用了react-dom的render函数而不是enzyme shallow-这有点作弊,因为render可能类似于完整的mount
import { act } from 'react-dom/test-utils';
import { render, unmountComponentAtNode } from 'react-dom';
// import your ChestWithToys component

let useEffect, container;

beforeEach(() => {
  // setup a DOM element as a render target
  container = document.createElement('div');
  document.body.appendChild(container);
});

afterEach(() => {
  // cleanup on exiting
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

it('tidies toys on unmount', () => {
  let handleTidyToys = jest.fn();
  useEffect = jest.spyOn(React, "useEffect");

  act(() => {
    render(<ChestWithToys toyBoxId={1} handleTidyToys={handleTidyToys} />, container);
  });

  // same as expect(handleTidyToys).to.have.callCount(0);
  expect(handleTidyToys).not.toHaveBeenCalled();

  unmountComponentAtNode(container);
  // same as expect(handleTidyToys).to.have.callCount(1);  
  expect(handleTidyToys).toHaveBeenCalled();
});
© www.soinside.com 2019 - 2024. All rights reserved.