ShallowWrapper::setState() 只能在类组件上调用

Pey*_*ian 4 javascript reactjs jestjs react-redux

在我使用withSnackbar. 但现在它失败了,我真的不知道如何解决这个问题。所以任何帮助将不胜感激。谢谢。

这是我在组件中的导出:

export default withSnackbar(StoryApp)
Run Code Online (Sandbox Code Playgroud)

这是我的测试:

let story = {
  Title: "title 1",
  body: "body 1",
  UserEntityKey: "userEntityKey",
  Key: "storyKey"
}

afterEach(() => {
  // cleaning up the mess left behind the previous test
  MockAxios.reset();
});

test('Story deletes based on mocked backend response', async () => {
  window.confirm = jest.fn()
  window.confirm.mockReturnValue(1);

  let idToken = "asdf"

  MockAxios.delete.mockImplementationOnce(() =>
    Promise.resolve(story.Key)
  )

  const storyApp = shallow(<StoryApp />);

  storyApp.setState((prev) => {
    prev.data.push(story)
    return prev
  })

  // Test without idToken
  await storyApp.instance().deleteStory(story)
  expect(MockAxios.delete).not.toHaveBeenCalled();
  expect(storyApp.state().data.length).toEqual(1)

  // Test with idToken
  storyApp.setState((prev) => {
    prev.user = { idToken: idToken }
    return prev
  })
  await storyApp.instance().deleteStory(story)
  expect(MockAxios.delete).toHaveBeenCalledWith(apiUrl + '?key=' + story.Key, { headers: { 'Authorization': idToken } });
  expect(storyApp.state().data.length).toEqual(0)
})
Run Code Online (Sandbox Code Playgroud)

这是输出:

? 基于模拟后端响应的故事删除

ShallowWrapper::setState() can only be called on class components

  101 |   const storyApp = shallow(<StoryApp />);
  102 | 
> 103 |   storyApp.setState((prev) => {
      |            ^
  104 |     prev.data.push(story)
  105 |     return prev
  106 |   })

  at ShallowWrapper.setState (node_modules/enzyme/build/ShallowWrapper.js:639:17)
  at Object.setState (__tests__/App.test.js:103:12)
  at tryCatch (node_modules/regenerator-runtime/runtime.js:62:40)
  at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:288:22)
  at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:114:21)
  at asyncGeneratorStep (__tests__/App.test.js:25:103)
  at _next (__tests__/App.test.js:27:194)
  at __tests__/App.test.js:27:364
  at Object.<anonymous> (__tests__/App.test.js:27:97)
Run Code Online (Sandbox Code Playgroud)

Est*_*ask 7

制作像StoryApplocal这样的原始类会损害可测试性。ImportedStoryApp是用withSnackbarHOC装饰的,不是类组件。

HOC 应该公开可用的原始组件,例如WrappedComponent属性。

或者一个模块应该导出装饰组件和原始组件:

export class StoryApp ...

export default withSnackbar(StoryApp)
Run Code Online (Sandbox Code Playgroud)

这样它可以被测试如下:

import StoryApp, { StoryApp as OriginalStoryAppClass } from '...';
...
const wrapper = shallow(<StoryApp />);
const storyApp = wrapper.find(OriginalStoryAppClass).dive();
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@estus,但现在我得到了其他东西:方法“dive”旨在在 1 个节点上运行。0 找到了。你是什​​么意思 OriginalStoryAppClass?可能类名是 StoryApp,所以我用它代替 OriginalStoryAppClass。 (2认同)