This is the first day of my participation in the August Text Challenge.More challenges in August
concept
Jest
: JestIs a set of testing framework, byFacebook
The tests includeReact
Apply to all of themJavaScript
The code.Jest
One idea is to provide a fully integrated “zero configuration” test experience.- The official recommendation
- Support for output of detailed code coverage reports
- powerful
mock
function - Flexible and convenient introduction of third-party libraries
react-testing-library
A:DOM
Test library, officially recommendedJest
Third party library, similar tojQuery
, provides more concise apis such as locating elements, assertions, and so on- Thought: distinguished fromenzyme.
react-testing-library
Write unit tests mainly from the user’s perspective, such as a “details” button, the function is to click the button will pop up, send a request, and then display page details; The idea I tested could be that the page has a button with the text of “details”. After clicking, the page will have a popup window with the popup content showing “…” ; Instead of worrying about the implementation details of the component’s internal code, for exampleprops
The value, etc. - Unit test writing ideas, referenceARRANGE-ACT-ASSERTmodel
- Arrange: Prepare something to be tested, for example
render
Output corresponding to the componentdom
Elements; For example, initialize some variable values - Act: Contains the functionality of the component, which may be user interactions such as
userEvent
:click
; Or sending asynchronous requestsasync... await
; Or call some method; - Assert that assertion
expect
Expected results.Act
And it can lead to certain desired reactions, likeclick
Post-page element changes; Data changes after an asynchronous request; Method calls, and so on;
- Arrange: Prepare something to be tested, for example
- Thought: distinguished fromenzyme.
Using the environment
- The project is installed by default if it is created using create-react-app
@ testing - library/jest - dom: "^ 5.14.1." "
@ testing - library/react: "^ 11.2.7"
@ testing - library/user - event: "^ 12.8.3"
- Additional dependencies can be added according to the specific situation of the project, such as:
@testing-library/react-hooks
- Can be in
package.json
addjest
(withscript
Peer), or add to the projectjest.config.ts
file"jest": { "verbose": true.// Whether to display test descriptions in descripe and test/it "collectCoverage": true.// Whether to output test code test coverage "setupFilesAfterEnv": [ "<rootDir>/src/setupTests.ts" // Call some default execution code file paths before each test file execution]},Copy the code
- The following for
verbose
Property is configured toFalse, true,
After the output information is different
- The following for
setupTests.ts
Examples of default execution code can be configured in the file
import React from 'react' import '@testing-library/jest-dom'; import { renderHook } from "@testing-library/react-hooks"; beforeEach(() = > { return renderHook(() = >{... })})...Copy the code
- For other configurations, please refer to the official website
- The following for
Knowledge:react-testing-library
- DOM API
- render:
function render( ui: React.ReactElement<any>, options? : {Is rarely used and contains configurable options such as Container and baseElement.}) :RenderResult // RenderResultReturns some element location methods:getByText,queryAllByTestIdEtc.eg:const {getByText, queryAllByTestId} = render(<Component />) // You can also call render directly, introducing the screen call Copy the code
Example:
// my-component.test.ts import {render} from '@testing-library/react' import userEvent from '@testing-library/user-event' import '@testing-library/jest-dom' import MyComponent from './my-component' // Use the render method to render the component or DOM, use positioning methods such as getByText to locate elements, and then assert test('test Hello World'.() = > { const {container, getByText} = render(<MyComponent/>) // Arrange expect(getByText('Hello World').toBeInTheDocument() }) Copy the code
- The cleanup:
- Unmounts React trees that were mounted with render
- Preventing memory leaks
Example:
import {render, cleanup} from '@testing-library/react' // Used in conjunction with the hook function, the previously rendered DOM is clear before each call to the test afterEach(cleanup) Copy the code
dom
Locating method-
-getByText: find by Element text content -getbyRole: find by aria role -getByLabelText: find by aria role -getByLabelText: find by label or aria-label text content -getByPlaceholderText: find by input placeholder value -getByAltText: find by img alt attribute -getByTitle: find by title attribute or svg title tag -getByDisplayValue: find by form element current value -getByTestId: find by data-testid attribute
-
QueryBy: Locate a dom element that does not exist on the page, return null if it does not exist, and do not throw an exception (same method as above)
-
FintBy: Locate asynchronous elements in the page, if not present, throw an exception (same as above)
-
Here are three main categories of method differences:
-
- render:
- Asynchronous method combination
async... await
use- WaitFor (Promise): Will wait until the inner function completes or an exception is thrown
- WaitForElementToBeRemoved (Promise) : internal function does not return until the Dom elements
- userEvent
click(element)
Click:dbClick
: double-clickasync type(element, text, [options])
: Enter textselectOptions(element, values)
: Form selectiontab({shift, focusTrap})
: Simulate TAB key (Switch focus)
- Added Jest snapshot tests
snapshot
import React from 'react'; import renderer from 'react-test-renderer'; import Link from '.. /Link.react'; it('renders correctly'.() = > { const tree = renderer .create(<Link page="http://www.facebook.com">Facebook</Link>) .toJSON() expect(tree).toMatchSnapshot() }) Copy the code
conclusion
Learn unit tests, combine the idea of arrange-act-Assert, master the API for each step according to the official documents, and write unit tests according to the user’s perspective. It is usually the following three steps:
- Arrange: Combine elements
render
.jest-dom
–getby/queryby/findby...
.jest.mock()
. , etc. - Act:
userEvent
.waitFor
.async... await
. , etc. - Assert:jest-dom-
toBeInTheDocument
.toBeChecked
, etc.
The resources
Rearrange – act-assert Jest official documentation testing-library official documentation arranging – act-assert