react jest测试_在React中进行测试,第3部分:Jest和Jest-Dom

本文是React中测试系列的第三部分,重点介绍如何使用Jest和Jest-Dom进行单元测试和断言。通过实例解析,帮助读者掌握在React应用中运用Jest进行有效测试的方法。
摘要由CSDN通过智能技术生成

react jest测试

Thus far in this series, we have covered the various types of testing and tools for React, and one of the most popular testing libraries, React Testing Library. If you have not read these, I recommend that you do so. Jest is used in conjunction with React Testing Library, and it is important that you understand both in order to understand testing through rendering component trees.

到目前为止,在本系列中,我们已经介绍了各种用于React 的测试和工具 ,以及最流行的测试库之一React Testing Library 。 如果您还没有阅读这些内容,建议您阅读。 Jest与React Testing Library一起使用,理解这两者很重要,以便通过渲染组件树来理解测试。

快速回顾 (A Quick Recap)

Testing rendered component trees with Jest and React Testing Library is all about testing the user experience. It is about testing that the app behaves the way that it should from the user’s standpoint, rather than testing the implementation of code.

使用Jest和React Testing库测试渲染的组件树就是测试用户体验。 从用户的角度测试应用程序的行为方式,而不是测试代码的实现。

In order to do this, you have to have two basic parts —a rendered element on which to perform tests (i.e., a component), and specific qualities or properties of DOM nodes to be tested (i.e., the presence of a button within the component).

为此,您必须具有两个基本部分:要在其上执行测试的呈现元素(即组件),以及要测试的DOM节点的特定质量或属性(即,零件)。

A simple way to think about React Testing Library and Jest is that React Testing Library handles the rendering of the element, and Jest handles the testing of the DOM nodes.

考虑React测试库和Jest的一种简单方法是,React Testing库处理元素的呈现,而Jest处理DOM节点的测试。

Jest-Dom (Jest-Dom)

Now technically, React Testing Library also provides some of the testing functionality through something called Jest-Dom. The documentation describes Jest-Dom as:

现在从技术上讲, React Testing Library还通过称为Jest-Dom的东西提供了一些测试功能。 该文档将Jest-Dom描述为:

a companion library for React Testing Library that provides custom DOM element matchers for Jest.

React Testing Library的配套库,为Jest提供自定义DOM元素匹配器。

A matcher, in plain english, is the element of a test that says something like .toEqual() or .toBeVisible. We’ll cover Jest-Dom briefly, but really it’s just an extended list that provides more options of different properties to test. The important thing to know is that it’s there for you when you need it, and if you can’t find what you’re looking for in Jest’s matchers, that Jest-Dom may have what you’re looking for.

用简单的英语匹配器是测试的元素,它说出类似.toEqual().toBeVisible 。 我们将简要介绍Jest-Dom,但实际上,它只是扩展列表,提供了更多可供选择的不同属性来进行测试。 要知道的重要一点是,当您需要时它就在您身边,如果您在Jest的匹配器中找不到所需的内容,则Jest-Dom可能会满足您的需求。

笑话 (Jest)

I think of Jest as being the tool to create the testing environment. It provides the context in which to render components for testing, and creates the test suites and test blocks.

我认为Jest是创建测试环境的工具。 它提供了呈现用于测试的组件的上下文,并创建了测试套件和测试块。

Jest can be configured either in your package.json file, a jest.config.js file, or the —-config <path/to/file.js|cjs|mjs|json> option. You can learn more about configuration here.

可以在package.json文件, jest.config.js文件或—-config <path/to/file.js|cjs|mjs|json>选项中配置Jest。 您可以在此处了解有关配置的更多信息。

测试套件 (Test Suites)

Test suite group together related tests. They are created using the describe function. describe accepts a string name/description and a function as its arguments: describe(name, fn).

测试套件将相关测试组合在一起。 它们是使用describe函数创建的。 describe接受字符串名称/描述和一个函数作为其参数: describe(name, fn)

测试用例 (Test Cases)

Test cases are the actual tests being grouped by the test suite. They are written using the test method which accepts a name, function, and optional timeout: test(name, fn, timeout).

测试用例是按测试套件分组的实际测试。 它们是使用test方法编写的,该方法接受名称,函数和可选的超时: test(name, fn, timeout)

For instance, you might write:

例如,您可以编写:

const isTruthy = true;describe('isTruthy variable', () => {
test('is true', () => {
expect(isTruthy).toBe(true);
});

test('is not false', () => {
expect(isTruthy).not.toBe(false);
})
})

匹配器 (Matchers)

The .toBe() above is called a matcher — this is that thing we referenced earlier, of which React Testing Library also provides a handful of through Jest-Dom. There is a long list of matchers available, from those validating truthiness and falsiness like .toBeNull() and .toBeDefined(), to those that validate numeric amounts like .toBeGreaterThan() and .toBeCloseTo(), to .toMatch() for string matching, .toContain() for arrays, and .toThrow() for error handling.

上面的.toBe()称为匹配器-这就是我们之前引用的内容,React Testing库也提供了其中的一些通过Jest-Dom。 还有很长的匹配器提供的名单,从这些验证感实性和falsiness像.toBeNull().toBeDefined()那些验证数字量像.toBeGreaterThan().toBeCloseTo().toMatch()字符串匹配, .toContain()用于数组, .toThrow()用于错误处理。

You can find the complete list of matchers provided by Jest here, and those provided by Jest-Dom here.

你可以找到玩笑提供的匹配的完整列表在这里 ,和那些玩笑-DOM提供了这里

异步测试 (Async Testing)

Like React Testing Library, Jest provides testing for code that runs asynchronously in JavaScript. Specifically, you can test callbacks, promises, and async/await.

像React Testing Library一样,Jest提供了对在JavaScript中异步运行的代码的测试。 具体来说,您可以测试回调,promise和async / await。

回呼 (Callbacks)

Callbacks can be tested by simply passing the done argument into the test function, rather than an empty argument. To use the above example, it would look like this:

可以通过简单地将done参数传递给测试函数而不是空参数来测试回调。 使用上面的示例,它看起来像这样:

const isTruthy = true;describe('isTruthy variable', done => {
test('is true', () => {
expect(isTruthy).toBe(true);
});

test('is not false', done => {
expect(isTruthy).not.toBe(false);
})
})

Now this is useless because we don’t use done here, but that’s what it would look like. I am going to borrow the examples from the documentation here, as there’s no better way to explain it. Below is an example in which fetchData() calls a callback function, callback() and the expectation is that the data will equal ‘peanut butter’. Your first instinct may be to test it like this:

现在这是没有用的,因为我们done这里不使用done ,但这就是它的样子。 我将在这里从文档中借用示例,因为没有更好的方法来解释它。 下面是一个示例,其中fetchData()调用一个回调函数callback() ,并且期望数据将等于“花生酱”。 您的第一个直觉可能是像这样测试它:

test('the data is peanut butter', () => {
function callback(data) {
expect(data).toBe('peanut butter');
} fetchData(callback);
});

But this won’t work. This is where you can use the done() callback. Jest knows to wait until done() has completed before finishing the test.

但这行不通。 在这里可以使用done()回调。 Jest知道要等到done()完成才可以完成测试。

test('the data is peanut butter', done => {
function callback(data) {
try {
expect(data).toBe('peanut butter');
done();
} catch (error) {
done(error);
}
}

fetchData(callback);
});

承诺 (Promises)

So long as your tests return a promise, Jest will know to wait for the promise to resolve before completing the test. If the promise is rejected, the test will fail. The above example, written using a promise instead, would look like this:

只要您的测试返回了承诺,Jest就会知道在完成测试之前要等到承诺被解决。 如果诺言被拒绝,则测试将失败。 上面的示例使用Promise编写,如下所示:

test('the data is peanut butter', () => {   
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});

异步/等待 (Async/Await)

A try/catch and/or await can be used inside of a test, so long as async is before the function. Like the promises implementation, this implementation is very similar to how you’d actually use async/await in code. The ‘peanut butter’ example would look like:

在测试内部可以使用try / catch和/或await ,只要在该函数之前使用async 。 像promises实现一样,该实现与您在代码中实际使用async / await的方式非常相似。 “花生酱”示例如下所示:

test('the data is peanut butter', async () => {   
const data = await fetchData();
expect(data).toBe('peanut butter');
}); test('the fetch fails with an error', async () => {
expect.assertions(1); try {
await fetchData();
} catch (e) {
expect(e).toMatch('error');
}
});

附加功能 (Additional Functionality)

We are going to focus on the testing described above — creating test suites containing test cases that use matchers to test values. In a future post, after covering Cypress, we will go over how to work React Testing Library into these tests in order to test DOM nodes. I want to call out though, even though we won’t cover it thoroughly, some of the additional functionality provided by Jest.

我们将专注于上述测试-创建包含使用匹配器测试值的测试用例的测试套件。 在以后的文章中,在介绍了赛普拉斯之后,我们将介绍如何将React Testing库工作到这些测试中,以测试DOM节点。 尽管我们不会全面介绍它,但我还是想讲一下Jest提供的一些附加功能。

快照 (Snapshots)

A typical snapshot test case for a mobile app renders a UI component, takes a snapshot, then compares it to a reference snapshot file stored alongside the test. The test will fail if the two snapshots do not match: either the change is unexpected, or the reference snapshot needs to be updated to the new version of the UI component.

移动应用程序的典型快照测试用例呈现了一个UI组件,拍摄了一个快照,然后将其与测试旁边存储的参考快照文件进行比较。 如果两个快照不匹配,则测试将失败:更改是意外的,或者参考快照需要更新为UI组件的新版本。

The above is from the Jest documentation. Snapshots, as it describes, are used to test that the UI has not unexpectedly changed. In React, this often involves creating and storing a snapshot of a serialized version of your React tree, which can then be compared to future serialized versions of that tree.

以上是来自Jest文档。 如描述的那样,快照用于测试UI是否意外更改。 在React中,这通常涉及创建和存储React树的序列化版本的快照,然后可以将其与该树的未来序列化版本进行比较。

You can learn more about snapshot testing here.

您可以在此处了解有关快照测试的更多信息。

设置和拆卸 (Setup and Teardown)

Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.

通常在编写测试时,您需要在测试运行之前进行一些设置工作,而在测试运行后需要进行一些整理工作。 Jest提供了辅助功能来处理此问题。

Jest provides a set of functions to handle actions that need to happen in order for tests to run, such as creating test data and clearing test data.

Jest提供了一组功能来处理为了运行测试而需要执行的操作,例如创建测试数据和清除测试数据。

You can learn more about setup and teardown testing here.

您可以在此处了解有关设置和拆卸测试的更多信息。

模拟 (Mocking)

Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new, and allowing test-time configuration of return values.

模拟函数允许您通过擦除函数的实际实现,捕获对该函数的调用(以及在这些调用中传递的参数),捕获用new实例化时的构造函数实例以及测试时配置来测试代码之间的链接。返回值。

In Jest, you can mock return values, function implementation, or entire modules, such as Axios. Mocking at its core is about isolating different elements in a larger scope, and testing those.

在Jest中,您可以模拟返回值,函数实现或整个模块,例如Axios。 模拟的核心是在更大范围内隔离不同的元素,然后进行测试。

You can learn more about mocking here.

您可以在此处了解有关嘲弄的更多信息。

Next we will cover a different type of testing — end to end testing, using Cypress. We will be circling back to both Jest and React Testing Library after that to go through writing and implement real world testing using all three tools.

接下来,我们将介绍另一种类型的测试-使用赛普拉斯的端到端测试。 之后,我们将循环回到Jest和React Testing库,以完成编写并使用所有这三种工具实施实际测试的过程。

翻译自: https://medium.com/javascript-in-plain-english/testing-in-react-part-3-jest-jest-dom-7a8a03ae60b

react jest测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值