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

时间:2019-03-20 17:15:31

标签: javascript reactjs react-redux jestjs

此测试在我使用withSnackbar之前通过了。但是现在失败了,我真的不知道该如何解决。因此,任何帮助将不胜感激。谢谢。

这是我在组件中的导出:

export default withSnackbar(StoryApp)

这是我的测试:

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)
})

这是输出:

●根据模拟的后端响应删除故事

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)

2 个答案:

答案 0 :(得分:2)

使用StoryApp之类的原始类会损害可测试性。导入的StoryAppwithSnackbar HOC装饰,不是类组件。

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

或者模块应同时导出装饰和原始组件:

export class StoryApp ...

export default withSnackbar(StoryApp)

这样可以像这样测试它:

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

答案 1 :(得分:0)

我的班级定义如下:

export class App extends React.PureComponent {}

和redux存储定义如下:

const AppStore = withDisclosureManager(connect(mapStateToProps, mapDispatchToProps)(injectIntl(AppStore)))

export default EditModeQuestionnaireSectionDetailsStore

当我用以下方式开玩笑地导入应用程序时:

// This doesn't works
import { App } from './App' 

// This works
import App from './App'