gpt4 book ai didi

reactjs - Jest/ enzyme 测试事件监听器已删除

转载 作者:行者123 更新时间:2023-12-03 14:26:58 24 4
gpt4 key购买 nike

学习 Jest 和 enzyme 来测试 React 应用程序,并使用 create-react-app 进行引导。

shallow之后使用unmount模拟add/removeEventListener会崩溃,并在mount之后使用unmount发出警告,见下文。有人知道我做错了什么吗?

我的测试:

it('should add and remove resize event handler', () => {
const adder = jest
.spyOn(global, 'addEventListener')
.mockImplementation(() => {});
const remover = jest
.spyOn(global, 'removeEventListener')
.mockImplementation(() => {});
const wrapper = shallow(<App />);
// this seems to work
expect(adder).toHaveBeenCalled();
// causing issues
wrapper.unmount();
expect(remover).toHaveBeenCalled();
});

mount之后使用unmount:

  console.error node_modules/fbjs/lib/warning.js:33
Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

Please check the code for the App component.

shallow之后使用unmount:

/home/nik/projects/learn/jest/node_modules/react-scripts/scripts/test.js:20
throw err;
^

Invariant Violation: ReactShallowRenderer render(): Invalid component element.
at invariant (/home/nik/projects/learn/jest/node_modules/fbjs/lib/invariant.js:42:15)
at ReactShallowRenderer.render (/home/nik/projects/learn/jest/node_modules/enzyme-adapter-react-16/node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:104:38)
at Updater.enqueueSetState (/home/nik/projects/learn/jest/node_modules/enzyme-adapter-react-16/node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:329:20)
at App.Object.<anonymous>.Component.setState (/home/nik/projects/learn/jest/node_modules/react/cjs/react.development.js:237:16)
at loadData.then.results (/home/nik/projects/learn/jest/src/App.js:15:12)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
error An unexpected error occurred: "Command failed.
Exit code: 1
Command: sh
Arguments: -c react-scripts test --env=jsdom
Directory: /home/nik/projects/learn/jest
Output:
".
info If you think this is a bug, please open a bug report with the information provided in "/home/nik/projects/learn/jest/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

最佳答案

我将卸载包装在 Promise 中

  return Promise.resolve().then(() => {
wrapper.unmount();
expect(remover).toHaveBeenCalled();
});

还错过了错误中的线索,“loadData” - 不是在 mock :

  jest.spyOn(App.prototype, 'loadData')
.mockImplementation(() => {
return new Promise(resolve => resolve([topics, subTopics]))
});

关于reactjs - Jest/ enzyme 测试事件监听器已删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50182297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com