gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:15:39 25 4
gpt4 key购买 nike

在我使用 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)

最佳答案

将像 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();

关于javascript - ShallowWrapper::setState() 只能在类组件上调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55266641/

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