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, byFacebookThe tests includeReactApply to all of themJavaScriptThe code.JestOne idea is to provide a fully integrated “zero configuration” test experience.
    • The official recommendation
    • Support for output of detailed code coverage reports
    • powerfulmockfunction
    • Flexible and convenient introduction of third-party libraries
  • react-testing-libraryA:DOMTest library, officially recommendedJestThird party library, similar tojQuery, provides more concise apis such as locating elements, assertions, and so on
    • Thought: distinguished fromenzyme.react-testing-libraryWrite 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 examplepropsThe value, etc.
    • Unit test writing ideas, referenceARRANGE-ACT-ASSERTmodel
      • Arrange: Prepare something to be tested, for examplerenderOutput corresponding to the componentdomElements; For example, initialize some variable values
      • Act: Contains the functionality of the component, which may be user interactions such asuserEvent:click; Or sending asynchronous requestsasync... await; Or call some method;
      • Assert that assertionexpectExpected results.ActAnd it can lead to certain desired reactions, likeclickPost-page element changes; Data changes after an asynchronous request; Method calls, and so on;

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 inpackage.jsonaddjest(withscriptPeer), or add to the projectjest.config.tsfile
    "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 forverboseProperty is configured toFalse, true,After the output information is different

    • The following forsetupTests.tsExamples 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

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
    • domLocating 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:

  • Asynchronous method combinationasync... awaituse
    • 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-click
    • async type(element, text, [options]): Enter text
    • selectOptions(element, values): Form selection
    • tab({shift, focusTrap}): Simulate TAB key (Switch focus)
  • Added Jest snapshot testssnapshot
       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 elementsrender.jest-domgetby/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