react mocha_使用Mocha和酶进行React单元测试

react mocha

by Michael Shilman

通过迈克尔·希尔曼(Michael Shilman)

使用Mocha和酶进行React单元测试 (React Unit Testing with Mocha and Enzyme)

在Meteor中进行UI测试的分步教程。 (A step-by-step tutorial for UI testing in Meteor.)

This is a short tutorial to help you test your React UI components. It presents a simple UI testing pattern I contributed to the Meteor Guide (?) and Todos sample app (?).

这是一个简短的教程,可以帮助您测试React UI组件。 它提供了一个简单的UI测试模式,该模式是我为《流星指南》 ( ?)和T odos示例应用程序(? )贡献的

You should read this if you:

如果您:

  1. Are using React to develop your apps

    使用React开发您的应用程序

  2. Want an easy way to automatically test your UI

    想要一种简单的方法来自动测试您的UI
  3. Are using Meteoror not — most of this will work in any React setup!

    使用流星 ... 或不 -这个最会工作在任何阵营的设置!

Here are the tests we’ll be writing on the left, and the UI components we’ll be testing on the right:

这是我们将在左侧编写的测试,而我们将在右侧进行测试的UI组件:

As we step through several tests in detail, you’ll learn the building blocks of React UI testing and best practices for how to structure a test suite. You can apply these patterns to your own apps to catch bugs, write code faster, document code behavior, and make sure things don’t break as you add new features to your app.

当我们详细完成几个测试时,您将学习React UI测试的构建模块以及有关如何构建测试套件的最佳实践。 您可以将这些模式应用于自己的应用程序,以捕获错误,更快地编写代码,记录代码行为,并确保在向应用程序中添加新功能时一切都不会中断。

The tutorial assumes a basic familiarity with React and ES6, but does not require much Meteor knowledge. All the source code is available in Meteor’s Todos sample app so you can run it on your own machine and play around with the code.

本教程假定基本熟悉React和ES6 ,但不需要太多的Meteor知识。 流星的Todos示例应用程序中提供了所有源代码,因此您可以在自己的计算机上运行它并试用这些代码。

UI单元测试 (UI Unit Testing)

There are many ways to test your software, but UI unit tests are small isolated tests of individual UI components, rather than full tests of the system. They are (relatively) easy to set up and fast to execute.

有很多测试软件的方法,但是UI单元测试是单个UI组件的小型隔离测试,而不是系统的完整测试。 它们(相对)易于设置且执行Swift。

Here’s a screen grab of the current suite of Todos unit tests, including both Client (UI) and Server tests. The entire suite runs in just over a second on my laptop:

这是当前Todos单元测试套件的屏幕截图,包括客户端(UI)和服务器测试。 整个套件在笔记本电脑上的运行时间仅超过一秒钟:

Because the tests run so quickly, you can run them every time you check in code or even every time you edit a file.

由于测试运行如此之快,因此您可以在每次签入代码时甚至在每次编辑文件时都运行它们。

Having a full test suite gives you piece of mind that your code is always working as you expect it to.

拥有完整的测试套件使您可以放心,您的代码始终可以按预期工作。

技术领域 (Technologies)

Before we jump in, a few words about the various open-source technologies in play:

在我们开始之前,请先介绍一下正在使用的各种开源技术:

Meteor is a full-stack Javascript platform for modern web and mobile applications. It runs Node.JS on the backend and any of several UI frameworks on the front-end including React. Testing got a huge boost in the recent 1.3 release, so we’re taking that for a spin today!

Meteor是用于现代Web和移动应用程序的全堆栈Javascript平台。 它在后端运行Node.JS,在前端运行多个UI框架中的任何一个,包括React。 在最近的1.3版本中 ,测试得到了巨大的推动,所以今天我们将其试用一​​下!

React is Facebook’s Javascript library for user interfaces. It’s a popular way to develop modern web interfaces, and with React Native is also making headway in native mobile and desktop apps.

React是Facebook的用于用户界面的Javascript库。 这是开发现代Web界面的一种流行方法,并且与React Native一起在本机移动和桌面应用程序中也取得了进展。

Mocha is the most popular Javascript unit test runner. Just like we won’t cover everything about testing, we won’t cover everything about unit testing in Mocha. But there should be enough here to give you a solid start.

Mocha是最受欢迎的Javascript单元测试运行程序。 就像我们不会涵盖测试的所有内容一样,我们也不会涵盖Mocha中的单元测试的所有内容。 但是这里应该有足够的空间来给您一个坚实的开始。

Enzyme is AirBnB’s library for unit testing React components. It’s great because it makes it easy to simulate the context of a React component without actually having to spin up a browser, and you can still perform CSS selection and simulate user events.

是AirBnB的库,用于对React组件进行单元测试。 很棒是因为它可以轻松模拟React组件的上下文,而无需实际启动浏览器,并且您仍然可以执行CSS选择并模拟用户事件。

Except for Enzyme, which is React-specific, all of these libraries operate independently from one another. Together they make a pretty great way to build realtime apps.

除了特定于React的酶以外,所有这些库都相互独立运行。 他们在一起是构建实时应用程序的绝佳方法。

?: Ok. Can we just start testing?

?:oķ。 我们可以开始测试吗?

If you have the Todos app set up on your machine, or don’t care about actually running the tests, you can skip to the next section. Otherwise let’s get your machine set up. ?

如果您在计算机上设置了Todos应用程序,或者不关心实际运行测试,则可以跳至下一部分。 否则,让我们安装机器。 ?

机器设置 (Machine Setup)

If you want to run the tests on your local machine, here’s the quick setup for Linux/Mac. For a much more more detailed walkthrough, the Meteor site provides a full tutorial for the Todos app:

如果要在本地计算机上运行测试,这是Linux / Mac的快速设置。 有关更详细的演练,Meteor网站提供了Todos应用程序完整教程

NOTE: there’s currently an issue where it gives the following warning on the command line when running the tests:

注意:当前存在一个问题 ,在运行测试时会在命令行上给出以下警告:

Unable to resolve some modules:"react/addons" in /path/to/react-compat.js"react/lib/ReactContext" in /path/to/react-compat.js"react/lib/ExecutionEnvironment" in /path/to/react-compat.js

It is safe to ignore this and you should be able to see the results of the test run in the browser at http://localhost:3000.

可以无视它,您应该能够在浏览器中的http:// localhost:3000上看到测试的结果

The test results are coming from any files with the suffix .tests.js in the source tree, and when we edit any files or add new files with that naming scheme, the test suite will automatically re-execute and update the browser window.

测试结果来自源代码树中带有后缀.tests.js的任何文件,并且当我们使用该命名方案编辑任何文件或添加新文件时,测试套件将自动重新执行并更新浏览器窗口。

NOTE: confusingly, there is also a tests/ directory in the top level of the source tree. This contains end-to-end tests, and you should ignore this for this tutorial. For more information see the guide.

注意:令人困惑的是,在源树的顶层还存在一个tests /目录。 它包含端到端测试,对于本教程,您应该忽略它。 有关更多信息, 请参见指南

组件渲染 (Component Rendering)

The simplest UI test is whether a component renders properly according to the data passed into it. For example, if you render a todo item, you’d expect to see the item’s name shown in the label, and it’s checked state to be reflected properly on the page.

最简单的UI测试是组件是否根据传递给它的数据正确呈现。 例如,如果渲染待办事项,则希望看到标签上显示该项目的名称,并且选中状态可以正确反映在页面上。

Here’s how that looks in Enzyme and Mocha:

这是酶和摩卡咖啡的外观:

There are a few things going on here.

这里发生了一些事情。

Structure. In Mocha, describe starts a test suite, and it starts a single test case. For our first test, we’re using the simplest possible structure. Note that the contents of describe and it are just functions, so we can do things like exit early to force the tests to only run on the client side.

结构体。 在摩卡, 描述开始一个测试套件,以及启动一个单个测试用例。 对于我们的第一个测试,我们使用的是最简单的结构。 请注意, describe的内容仅仅是函数,因此我们可以执行诸如早退出之类的操作以强制测试仅在客户端运行。

Within each test, we follow a setup → exercise → verify → teardown pattern which comes under different names, but is the common best practice in unit testing:

在每个测试中,我们遵循一个设置→练习→验证→拆卸模式,该模式使用不同的名称,但这是单元测试中常见的最佳实践

Setup. First we create the data to render, which in this case is a Javascript object. Easy peasy.

建立。 首先,我们创建要渲染的数据,在本例中为Javascript对象。 十分简单。

Exercise. Next use the shallow function to render the data into a component. This rendering is what we’re actually testing, so that’s why it’s part of the exercise phase rather than setup. Calling shallow returns an Enzyme wrapper object that contains the rendered component instance, as well as a bunch of utility functions to simulate user events like mouse clicks and query the UI state.

行使。 接下来,使用shallow函数将数据呈现到组件中。 我们实际上正在测试此渲染,因此这就是为什么它是练习阶段而不是setup的一部分。 呼唤 返回一个酶包装器对象,其中包含呈现的组件实例,以及一堆实用程序函数来模拟用户事件,例如鼠标单击并查询UI状态。

Verify. Next, we use hasClass, find, and prop to query the UI state to verify that the component has rendered properly. All TodoItem instances should have the list-item class, and checked items should have the checked class. Finally we make sure that the default value of the input is “Embrace the Ecosystem” as we’d expect.

校验。 接下来,我们使用hasClassfindprop查询UI状态以验证组件已正确呈现。 所有TodoItem实例都应具有list-item类,而选中的项应具有checked类。 最后,我们确保输入的默认值是我们期望的“拥抱生态系统”。

Teardown. In many tests there’s also some cleanup to do, but in this case there’s nothing to clean up since all the variables are temporary.

拆除。 在许多测试中,还需要进行一些清理,但是在这种情况下,由于所有变量都是临时变量,因此无需清理。

To add this test to the Todos app, simply copy the snippet into a file imports/ui/components/TodoItem-render.tests.js underneath the todos directory (any file with the .tests.js suffix actually, but we put it in the same directory as the component by convention). This test will be redundant with the tests already in TodoItem.tests.js, but now you know how to add your own.

要将此测试添加到Todos应用程序,只需将代码段复制到todos目录下的文件imports / ui / components / TodoItem-render.tests.js (实际上任何后缀为.tests.js的文件,但我们将其放入按照约定与组件位于同一目录)。 与TodoItem.tests.js中已经存在的测试相比 ,该测试将是多余的,但是现在您知道了如何添加自己的测试。

用状态渲染 (Rendering with State)

Let’s do another example that’s slightly more complex. The list header actually has two states: a normal state and an editing state, and it displays two different UI’s depending on internal component state.

让我们再做一个稍微复杂一点的例子。 列表标题实际上具有两种状态:正常状态和编辑状态,并且根据内部组件状态显示两个不同的UI。

And here’s how the test looks:

这是测试的外观:

Structure. Notice that we’ve split the code up into two describe blocks to give it a little more structure. This will help when we start adding more tests, since in addition to rendering differently, the component’s interaction changes depending on the state. We’ll talk about this more below.

结构体。 请注意,我们已将代码分成两个describe块,以使其更具结构性。 当我们开始添加更多测试时,这将有所帮助,因为除了呈现方式不同之外,组件的交互还根据状态而变化。 我们将在下面进一步讨论。

Setup/Exercise. Business as usual, except that we’ve used Enzyme’s mount function to render rather than shallow, which we used above. We use mount to simulate the full component context. The difference is that shallow only renders the component passed, but mount requires that we are running in a browser context (browser or headless browser) and also renders child components.

设置/锻炼。 一切照旧,只不过我们使用的酶的装载功能来呈现,而不是肤浅 ,我们在上面使用。 我们使用mount模拟整个组件上下文。 区别在于, 浅层仅渲染通过的组件,而挂载要求我们在浏览器上下文(浏览器或无头浏览器)中运行,并且还渲染子组件。

Test. We’ve used Enzyme’s setState utility to manipulate the component state. This is like simulating a mouse click, except for rather than simulating the user directly, we are simulating a change from another part of the application.

测试。 我们已经使用了Enzyme的setState实用程序来操纵组件状态。 这就像模拟鼠标单击,除了模拟应用程序的其他部分,而不是直接模拟用户之外,这只是模拟。

Verify/Teardown. Nothing special: querying the DOM and no cleanup required for this simple test.

验证/拆卸。 没什么特别的:查询DOM,此简单测试不需要清理。

用户互动 (User Interaction)

Rendering is only half of the equation, and things get more interesting when we want to test user interaction. First, let’s model when a user clicks the checkbox on a todo item:

渲染只是等式的一半,当我们要测试用户交互时,事情变得更加有趣。 首先,让我们对用户单击待办事项上的复选框进行建模:

And here’s how that test looks:

这是该测试的外观:

Structure. This code follows the same setup → exercise → verify → teardown structure as above, but in this case we actually get to do something meaningful in each step.

结构体。 该代码遵循与上述相同的设置→练习→验证→拆卸结构,但是在这种情况下,我们实际上在每一步中都要做有意义的事情。

Setup. This one is interesting because when you click on the checkbox, the component actually calls a Meteor Method, which asks the server to update the database. However, when we’re running a unit test there is no server, and even if there was we wouldn’t want to modify any data. So we stub out the method using the Sinon library (commonly used with Mocha). It replaces the setCheckedStatus method’s call function with a dummy that looks like the original, but simply records the user’s behavior and doesn’t actually do anything with it.

建立。 这很有趣,因为当您单击复选框时,该组件实际上调用了Meteor Method ,它要求服务器更新数据库。 但是,当我们运行单元测试时,没有服务器,即使有,我们也不想修改任何数据。 因此,我们使用Sinon库(通常与Mocha一起使用)对方法进行了测试。 它将setCheckedStatus方法的调用函数替换为看起来像原始对象的虚拟对象,但仅记录用户的行为并且实际上不对其执行任何操作。

NOTE: You may be scratching your head because up until now, the shallow/mount rendering has been part of the exercise phase, but this time around it’s in setup. It’s a subtle point, but since the focus of this test is the user interaction action so rendering is just part of the setup.

注意:您可能会挠头,因为到目前为止, 浅/固定渲染一直是练习阶段的一部分,但这一次是在设置中 。 这是一个微妙的要点,但是由于此测试的重点是用户交互操作,因此渲染只是设置的一部分。

Exercise. Next, we use the simulate function to make the click. Pretty straightforward. We can also simulate keyboard events, form submissions and so forth, but we don’t need that for this test.

行使。 接下来,我们使用模拟功能进行点击。 非常简单。 我们还可以模拟键盘事件,表单提交等,但是在此测试中我们不需要这样做。

Verify. Now we we can see how the stub comes into play. We assert that the setCheckedStatus method was called with the arguments we expect. This not only tests the behavior but provides nice documentation about how the interaction works.

校验。 现在我们可以看到存根如何发挥作用。 我们断言,使用我们期望的参数调用了setCheckedStatus方法。 这不仅可以测试行为,而且可以提供有关交互作用的出色文档。

Teardown. Setting up the stub actually modifies the setCheckedStatus method globally, so at the end of the test we should clean it up. restore replaces the stub with the original function.

拆除。 设置存根实际上是在全局范围内修改setCheckedStatus方法,因此在测试结束时,我们应该对其进行清理。 restore将存根替换为原始功能。

All of our other interaction tests follow the same basic structure and you can see them in the Todos repo.

我们所有其他的交互测试都遵循相同的基本结构,您可以在Todos存储库中看到它们。

测试套件结构 (Test Suite Structure)

Using these basic patterns above for testing rendering and interaction, you should be able to test any React component in the Todos example and easily adapt the pattern to your own apps. But if you start adding tests willy-nilly, without some way of structuring your code, things will quickly get out of control. So I’ll wrap up the tutorial by describing a higher-level test structure.

使用上面的这些基本模式来测试渲染交互 ,您应该能够测试Todos示例中的任何React组件,并可以轻松地将模式适应您自己的应用程序。 但是,如果您开始随意添加测试,而没有某种结构化代码的方式,那么事情很快就会失去控制。 因此,我将通过描述更高级别的测试结构来结束本教程。

I mentioned above how using Mocha’s describe can both delineate a logical structure and also save code, and we’ll use that to our advantage as we add more tests. Let’s see how that works.

上面我提到了如何使用Mocha的describe既可以描述逻辑结构又可以保存代码,并且随着我们添加更多测试,我们将利用它的优势。 让我们看看它是如何工作的。

Recall our ListHeader example above where we distinguished between the the default and editing states. The test had the following structure:

回顾上面的ListHeader示例,在其中我们区分了默认状态和编辑状态。 该测试具有以下结构:

Now let’s refactor the code using Mocha’s beforeEach construct which gets executed before each of the tests inside the describe suite:

现在,让我们使用Mocha的beforeEach构造重构代码, 构造在describe套件内的每个测试之前执行:

At first glance, this change appears to be a net loss: the code got longer and a complicated. However, the more tests we add, the more reuse we get and the more this structure starts to make sense. Here is the test structure in the Todos app, and this is only a partial test of the header’s functionality:

乍一看,这种变化似乎是净损失:代码变得更长且复杂。 但是,添加的测试越多,获得的重用就越多,这种结构就越有意义。 这是Todos应用程序中的测试结构,这只是对标头功能的部分测试:

Before you go all code cowboy with this, you should note that because beforeEach executes for every test in every nested block, it’s very easy to write inefficient tests this way. For example, in the code above a new React router stub is created five times, once for every single it test, although it’s really only needed for one of the tests. In this case, I was fine with that. However, it’s tempting to throw all your test setup into beforeEach, but you should generally only put what you need there.

在进行所有代码编写之前,您应该注意,因为beforeEach在每个嵌套块中为每个测试执行,所以以这种方式编写效率低下的测试非常容易。 例如,在上述新的代码阵营路由器存根创建五次,一次为每一个的测试,虽然它真的只需要其中一个测试。 在这种情况下,我对此表示满意。 但是,将所有测试设置都放到beforeEach中是很诱人的,但是通常只应将所需的内容放在这里。

结论和后续步骤 (Conclusion and Next Steps)

In this tutorial, we’ve gone through the basics of UI Component testing, with well-documented examples of how to test rendering and interaction. These are the basic building blocks for testing your UI, and using them you should be able to unit test most aspects of any React UI you develop.

在本教程中,我们介绍了UI组件测试的基础知识,并提供了详细记录如何测试渲染和交互的示例。 这些是测试UI的基本构建块,使用它们,您应该能够对开发的任何React UI的大多数方面进行单元测试。

Here are some next steps to learn more:

以下是一些进一步了解步骤:

  1. Your homework. Check out the Todos app, and add a unit test for a different behavior. For example, the app distinguishes between public and private Todos, but the current tests don’t cover that. Add a test for that! Extra credit: submit a pull request!

    你的作业Todos应用程序 ,并添加针对不同行为的单元测试。 例如,该应用程序可区分公共待办事项和私人待办事项,但当前的测试并未涵盖这一点。 为此添加测试! 额外的信用:提交拉取请求!

  2. More React UI Testing. Fellow Meteor geek Arunoda’s UI Testing in React covers a lot of the same ground, but from a different angle. And if you’re so inclined, Ken Wheeler explains a similar setup for Unit Testing React Native.

    更多React UI测试。 流星怪胎Arunoda 在React中进行UI测试涵盖了很多相同的方面,但是角度不同。 而且,如果您愿意的话, Ken Wheeler会单元测试React Native解释类似的设置。

  3. Testing in General. UI unit testing is just a piece of the puzzle. Eric Elliott gives five questions to answer in each unit test. The Meteor Guide’s testing section is a great overview of other kinds of tests in Meteor, and of testing in general.

    一般测试。 UI单元测试只是一个难题。 埃里克·埃利奥特(Eric Elliott)在每个单元测试中都会回答五个问题。 《 Meteor Guide》的“ 测试”部分很好地概述了Meteor中的其他各种测试以及一般的测试。

Comment below with questions or suggestions. And follow me here or on Twitter for more great articles coming down the pipe.

在下面用问题或建议发表评论。 并在这里或在Twitter上关注我, 获取更多精彩文章。

And finally, if this was useful, please tap the ? button below. Thanks!

最后,如果这很有用,请点击? 下方的按钮。 谢谢!

Many thanks to Tom Coleman for Meteor/PR guidance; Sean Moon for introducing me to testing; Keywon, Ross Geesman, Josh Owens, Sam Hatoum for excellent feedback on the draft.

非常感谢Tom Coleman对流星/公关的指导; 肖恩·穆恩 ( Sean Moon)向我介绍了测试; KeywonRoss GeesmanJosh OwensSam Hatoum对该草案提供了出色的反馈。

翻译自: https://www.freecodecamp.org/news/react-unit-testing-with-mocha-and-enzyme-77d18b6875cb/

react mocha

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值