Javascript 测试在Ezyme中使用acts调用的useEffect卸载回调
我有一个具有这种设置的组件Javascript 测试在Ezyme中使用acts调用的useEffect卸载回调,javascript,reactjs,enzyme,react-hooks,react-dom,Javascript,Reactjs,Enzyme,React Hooks,React Dom,我有一个具有这种设置的组件 const ChestWithToys = ({toyBoxId, handleTidyToys})=> { /* do stuff with toys */ useEffect(() => () => handleTidyToys(), [toyBoxId]) } 这是我用酶和act进行的测试(来自react dom/test utils) it('卸载时整理玩具',()=>{ 让handleidyToys=sinon.stub(
const ChestWithToys = ({toyBoxId, handleTidyToys})=> {
/* do stuff with toys */
useEffect(() => () => handleTidyToys(), [toyBoxId])
}
这是我用酶和act进行的测试(来自react dom/test utils
)
it('卸载时整理玩具',()=>{
让handleidyToys=sinon.stub();
让包装器=浅();
expect(handleitytoys).to.have.callCount(0);
行动(()=>{
wrapper.unmount();
});
期望(手持玩具).to.have.callCount(1);
});
该组件按预期运行。但是,在测试中,从未调用handleitytoys
。有什么好处?我找不到更好的卸载位置,但从我看到的情况来看,这应该会触发我的清理回调
如果我用setProps
替换卸载并更改queryId,它仍然不会触发
是酶不相容,还是我犯了其他错误
编辑:我刚刚在useEffect中删除了一堆console.log,但它根本没有运行。这是一种适合我的方法,但有一些注意事项:
jest
来监视和嘲弄,而不是sinon
李>
render
函数,而不是函数
——这有点作弊,因为render
可能类似于fullmount
:从'react dom/test utils'导入{act};
从“react dom”导入{render,unmountComponentAtNode};
//导入您的ChestWithToys组件
让我们使用效果,容器;
在每个之前(()=>{
//将DOM元素设置为渲染目标
container=document.createElement('div');
文件.正文.附件(容器);
});
之后(()=>{
//退出时的清理
卸载组件节点(容器);
容器。移除();
container=null;
});
它('卸载时整理玩具',()=>{
让handleidytoys=jest.fn();
useffect=jest.spyOn(反应,“useffect”);
行动(()=>{
渲染(,容器);
});
//与expect(handleTidyToys.to.have.callCount)相同(0);
期望(手持玩具)。而不是。已装入();
卸载组件节点(容器);
//与expect(handleTidyToys.to.have.callCount)相同(1);
期望(手持玩具)。已装入();
});
如果调用wrapper.unmount(),会发生什么代码>直接而不是使用act
@Rikin,如果我使用act
运行它,这没有什么不同。后来我发现问题是我需要使用mount
而不是shallow
,一旦它工作了,我会把它写进一个答案中。@Rikin事实证明,该组件当前还有一个挂起的组件,它不能与mount一起工作。
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);
});
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();
});