酶/ Jest反应测试-浅连接的组件,带有react-redux> 6 [英] Enzyme/Jest React Testing - Shallow connected component with react-redux > 6

查看:95
本文介绍了酶/ Jest反应测试-浅连接的组件,带有react-redux> 6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用酶和Jest进行测试。
在我们的代码库中更新到了最新版本的react-redux,所有连接的组件测试用例开始失败(版本6)。
使用

We use Enzyme and Jest for testing. Updated to the latest version of react-redux in our code base, and all of the connected component test cases started failing (Version 6). Using

import { createMockStore } from 'redux-test-utils';

创建商店

测试用例使用较旧的版本:

Test cases that worked with older version:

const wrapper = shallow(<SomeConnectedComponent />, {context: { store }});

无法给出错误

不变违规:在 Connect(SomeConnectedComponent)的上下文中找不到存储。

读了几篇文章,得到了安装和安装的建议用提供程序包装器包装

Reading few posts, got a suggestion to mount and wrap with provider wrapper

const wrapper = mount(<Provider store={store}><SomeConnectedComponent /></Provider>);

以上代码可以工作,但是我希望它可以与swallow一起用于单元测试。

Above code works, but I want it to work with swallow for unit testing.

编辑:

const wrapper = shallow(<Provider store={store}>
<SomeConnectedComponent />
</Provider>)

上面的代码返回空的shallowWraper对象。

Above code returns empty shallowWraper object.

使用react-redux版本> 6吞咽已连接组件的最佳方法是什么

What is the best way to swallow connected component with react-redux version > 6

推荐答案

Shallow不适用于最新版本的react-redux。
从6.x版本开始,会引起上述问题。

Shallow does not work with the latest version of react-redux. From Version 6.x, it causes the mentioned problem.

我发现最好的解决方案是使用较旧版本的react-redux进行测试,
和较新的版本作为实际代码。

The best solution I found was to use a older version of react-redux for testing, and the newer one for actual code.

1)将较旧的版本添加为dev依赖项。因为那里有较新版本的react-redux,所以您将需要使用别名。可以是任何版本5.x。它将安装 react-redux-test

1) Add the older version as a dev dependency. Because a newer version of react-redux is there you will need to use a alias. This can be any version 5.x This will install "react-redux-test"

yarn add react-redux-test@npm:react-redux@5.0.6 -D

2)在_模拟_文件夹下,创建新文件react-redux.js并从内部导出旧版本

2) Under the _ mocks _ folder, create a new file react-redux.js and export the older version from within

export * from 'react-redux-test';

默认情况下,此模拟将在每个测试用例文件中使用,因此旧的测试代码不再中断

This mock will be used in every test case file by default, so the old testing code no longer breaks.

但是,如果您想使用新的react-redux库进行测试,则可以使用

If however you want to test with the new react-redux library, you can use

jest.unmock('react-redux')

在新测试之上文件。

升级后,有数百个测试失败,这种方法对我有用,因为我也想在新组件中使用Hooks Api。

After upgrading there were hundreds of tests failing, this approach works for me as i want to use the Hooks Api in new components as well.

这样,您可以使用新库中的功能,直到酶/ react-redux修复为止。

This way you can use features the new library until enzyme / react-redux come up with a fix.

这篇关于酶/ Jest反应测试-浅连接的组件,带有react-redux&gt; 6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆