react测试组件_React测试库以现代方式测试React组件

react测试组件

Unit testing, and in our case, testing components, is a key element of any scalable and maintainable project. That truism is even more obvious now in the age of independent and shareable components. When sharing components between projects, testing serves as a way to both validate that a component behaves as expected and that it is independent and reusable (otherwise it would show to be very difficult to test).

单元测试以及我们的示例测试组件是任何可扩展和可维护项目的关键要素。 在独立和可共享的组成部分的时代,这种直言不讳的现象现在更加明显。 在项目之间共享组件时 ,测试是一种验证组件行为是否符合预期以及是否独立且可重用的方法(否则,将很难进行测试)。

Image for post
React components shared from different projects to Bit.dev (using Bit)
React从不同项目共享的组件到 Bit.dev (使用 Bit )

When it comes to testing React components, one of the most popular testing frameworks is Enzyme. But if you start a brand new project using thecreate-react-appcommand-line tool, what you would see is the React Testing Library (RTL). It’s not just another testing utility. This library promotes a different way of testing React components. If we take a closer look, it makes it much easier to test these components.

在测试React组件时,最流行的测试框架之一是Enzyme。 但是,如果您使用create-react-app命令行工具启动一个全新的项目,您将看到的是React Testing Library(RTL)。 它不仅仅是另一个测试实用程序。 这个库促进了测试React组件的另一种方式。 如果我们仔细观察,它会更容易测试这些组件。

1.酶的挑战 (1. The challenge with Enzyme)

Let’s have a look a the challenges with the current testing approach using a practical example.

让我们通过一个实际的例子来看看当前测试方法所面临的挑战。

Just imagine, you write your unit tests based on CSS class selectors. In a later stage, a refactoring happens, and bam !!! all your tests are failing now.

试想一下,您基于CSS类选择器编写了单元测试。 在稍后的阶段,发生了重构,而且很糟糕! 您的所有测试现在都失败了。

The same thing happens when you depend on props and state in your tests. Here the tests are more tightly coupled with implementation details. Hence, it becomes less maintainable. We need unit tests to gain more confidence over how stable our codebase is. And at the same time, if our unit tests are more closer to what user experience, we will be more confident in our code. These are the simple driving factors when using RTL. If that doesn’t make sense yet, don’t worry. This article is all about explaining that.

当您依赖测试中的道具和状态时,也会发生同样的事情。 这里的测试与实现细节紧密结合。 因此,它变得难以维护。 我们需要单元测试,以便对我们的代码库的稳定性有更多的信心。 同时,如果我们的单元测试更接近于用户体验,我们将对代码更有信心。 这些是使用RTL时的简单驱动因素。 如果那还没有意义,请不要担心。 本文都是关于这一点的说明。

酶的作用 (How Enzyme Works)

What we have in Enzyme is something like below.

我们在酶中的功能如下。

it('simulates click events', () => {
const onButtonClick = sinon.spy();
const wrapper = mount((
<Foo onButtonClick={onButtonClick} />
));
wrapper.find('#foo').simulate('click');
expect(onButtonClick).to.have.property('callCount', 1);
});

But the problem is that the test depends on the button having an HTML attribute “id” with the value “foo” specified in the HTML markup.

但是问题在于测试取决于具有HTML标记中指定的值为“ foo”HTML属性“ id”的按钮。

React测试库(RTL)的工作方式 (How the React Testing Library (RTL) Works)

In HTML, the “id” attribute isn’t something a user would see visually. Instead, a user would see a button text, read it, and then perform a click, as shown below.

在HTML中,“ id”属性不是用户可以看到的。 而是,用户将看到按钮文本,阅读该文本,然后单击,如下所示。

fireEvent.click(getByText(/Fetch Some Metal Music/i));

Instead of depending on implementation details, it depends on what actual user might see.

与其依赖于实现细节,不取决于实际用户可能看到的内容。

Let’s take an example to understand this better.

让我们举个例子来更好地理解这一点。

We have a simple component, where we have a button, which the user can clicks and view a list of metal genres. Here, we are using a music-genre service to get these music genres. Just think of it as an asynchronous API call. For clarity, I have come up with something like below.

我们有一个简单的组件,其中有一个按钮,用户可以单击该按钮并查看金属类型的列表。 在这里,我们使用音乐流派服务来获取这些音乐流派。 只需将其视为异步API调用即可。 为了清楚起见,我想出了类似下面的内容。

To make it more realistic, we’ve made 1000ms latency to the service. Now if we start to write tests, in the way how we used to do it.

为了使其更加真实,我们为该服务设置了1000ms的延迟。 现在,如果我们开始以以前的方式编写测试。

2.测试范围 (2. The Scope of Testing)

Let’s take an example scenario of listing metal genres.

让我们以列出金属类型的示例场景为例。

  1. Initially, we need to see a title.

    最初,我们需要看到一个标题。
  2. A user should be able to click the button for fetching metal genres and component should properly call the service (well we can divide this into two. Wouldn’t that be overkill? ).

    用户应该能够单击用于获取金属类型的按钮,并且组件应该正确调用该服务(好吧,我们可以将其分为两部分。这不是很过分吗?)。
  3. Users should be able to view the list of metal genres.

    用户应该能够查看金属类型的列表。
  4. If it failed to fetch metal genres, the user should see a proper error message.

    如果无法获取金属类型,则用户应该看到正确的错误消息。

用酶测试 (Testing with Enzyme)

Let’s write some of the test cases to test the scenarios with Enzyme.

让我们编写一些测试用例,以使用Enzyme测试场景。

Here we do a shallow rendering and see whether we have the initialization stage correctly. We have also mocked the service. When we perform a click event, it calls the service.

在这里,我们进行一个浅表渲染,看看我们是否正确地完成了初始化阶段。 我们也嘲笑了这项服务。 当我们执行click事件时,它将调用该服务。

使用React Testing Library(RTL)进行测试 (Testing with React Testing Library (RTL))

However, we can similarly do the same using the RTL. Let’s try it for all the scenarios described above.

但是,我们可以类似地使用RTL进行相同的操作。 让我们针对上述所有场景进行尝试。

And you can see, instead of selectors in Enzyme, what we have is;

您会看到,我们所拥有的是代替酶中的选择器的;

getByText, findByText, getAllByRole etc 

The difference is that these are similar to what an actual user sees on a screen. But here we can improve this more, and what you have seen here is just converting a whole set of Enzyme tests to RTL tests. And you will see a bunch of warning messages even though all the tests were running correctly, instructing to use ‘act(…)’ as a wrapper.

区别在于它们类似于实际用户在屏幕上看到的内容。 但是在这里,我们可以进一步改进它,而您在这里看到的只是将整套酶测试转换为RTL测试。 即使所有测试都在正确运行,您也会看到一堆警告消息,指示使用“ act(…)”作为包装器。

Image for post

There are many ways that we can get around these warnings. Simplest is to turn off the warnings 😆. Just kidding!!

我们可以通过多种方式解决这些警告。 最简单的方法是关闭警告😆。 开玩笑!!

The best way is to follow RTL recommendations to Write fewer, longer tests.

最好的方法是遵循RTL建议编写更少,更长的测试

3.使用RTL为用户方案编写测试 (3. Write Tests for User Scenarios Using RTL)

This approach encourages testing a whole user flows over testing individual pieces of functionalities. Let’s write down two user flows that we can see here.

这种方法鼓励测试整个用户流而不是测试各个功能。 让我们写下两个我们可以在此处看到的用户流。

  1. A user can click the fetch button and see a list of metal genres (we can include initial state and the loading in the same flow)

    用户可以单击“获取”按钮并查看金属类型的列表(我们可以在同一流程中包括初始状态和负载)
  2. A user can click the fetch button and see a proper error message if there’s an error fetching the metal genres.

    如果在获取金属类型时发生错误,则用户可以单击“获取”按钮并看到正确的错误消息。

Let’s test these two scenarios.

让我们测试这两种情况。

It will remove the warnings and give more confidence since the tests are much closer to how an actual user might interact with our component.

由于测试与实际用户与我们的组件的交互方式非常接近,因此它将消除警告并提供更多的信心。

You can find the small Application that we used to explain here. There are three branches.

您可以在此处找到我们用来解释的小型应用程序。 有三个分支。

  1. Master — How we supposed to do it.

    大师-我们应该怎么做。
  2. Enzyme-way — depicts a little bit of how we used to do it.

    酶法-描述了我们过去的用法。
  3. Bad-way — well, we are not encouraged to do it in this way. But no one can blame you if you do this.

    坏路-好吧,我们不鼓励这样做。 但是如果您这样做,谁也不能怪你。

Happy maintainable unit testing ❤️

快乐的可维护单元测试❤️

学到更多 (Learn More)

翻译自: https://blog.bitsrc.io/react-testing-library-the-modern-way-to-test-react-components-778ef578d0d9

react测试组件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值