• [Jest] Note


    Must have

    Configure Jest to Run Setup for All Tests with Jest setupFilesAfterEnv

    We want to include '@testing-library/jest-dom'so that we can have such syntax and better error message:

    expect(button).toHaveTextContent('Submit')

    To enable that we need to install npm i --save-dev @testing-library/jest-dom

    And how to setup:

    https://github.com/testing-library/jest-dom

     

    Support a Test Utilities File with Jest moduleDirectories

    Every large testbase has common utilities that make testing easier to accomplish. Whether that be a custom render function or a way to generate random data. Let’s see how we can make accessing these custom utilities throughout the tests easier using Jest’s moduleDirectories feature.

    create a test util file, example:

    import React from 'react'
    import PropTypes from 'prop-types'
    import {render as rtlRender} from '@testing-library/react'
    import {render} from '@testing-library/react'
    import {ThemeProvider} from 'emotion-theming'
    import {dark} from '../src/themes'
    
    function render(ui, {theme = themes.dark, ...options}) {
      function Wrapper({children}) {
        return <ThemeProvider theme={theme}>{children}</ThemeProvider>
    }
    Wrapper.propTypes = {
      children: PropTypes.node,
    }
      return rtlRender(ui, {wrapper: Wrapper, ...options}}
    }
    
    export * from '@testing-librasry/react'
    export {render}

    For easy import test util, we need to modify jest.config.js

    moduleDirectories: [
      'node_modules',
      path.join(__dirname, 'src'),
      'shared',
      path.join(__dirname, 'test'), // <-- anything lives in test directors can be imported as node_modules
    ],

    To resolve eslint issue:

    npm install --save-dev eslint-import-resolver-jest

    Eslint config:

      overrides: [
        {
          files: ['**/src/**'],
          settings: {'import/resolver': 'webpack'},
        },
        {
          files: ['**/__test__/**'],
          settings: {
            'import/resolver': {
              jest: {
                jestConfigFile: path.join(__dirname, './jest.config)
            },
        }},
      ],

    To enable Editor redirection for the file shortcut

    Add testfolder into tsconfig.json :

    {
      "compilerOptions": {
        "baseUrl": "./",
        "paths": {
          "*": ["src/*", "src/shared/*", "test/*"]
        }
      },
      "include": ["src", "test/*"]
    }

    Support Running Multiple Configurations with Jest’s Projects Feature

    `displayName` for each project jest.config.js.

    Jest Snapshots

    Snapshot testing is a way to simplify writing and maintaining assertions. As noted in the Jest documentation: “The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses pretty-format to make snapshots human-readable during code review. On subsequent test runs Jest will simply compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code that should be fixed, or the implementation has changed and the snapshot needs to be updated.” Let’s see how these work and in what situations we can and should use them.

    This lesson uses a simple demo before hopping into the application code testing DOM nodes. This example code isn't available.

    update snapshot:

    npm t -- -u

    Diff between toMatchSnapshot()vs toMatchInlineSnapshot()

    toMatchSnapshotKeep snapshot and your test code in two differents files

    toMatchInlineSnapshot Keep snapshot and your test code in the same file.

    https://jestjs.io/docs/snapshot-testing

    CSS-in-JS class name problem

    Part of the power of snapshots is the ability to provide custom serializers. Let’s check out how to use jest-emotion to include our emotion CSS styles in our React component snapshots so we can be made aware of the impact of our CSS changes on our components.

    Check this page about how to install and fix the problem.

    Custom Module Resolution with Jest moduleDirectories

    Webpack’s resolve.modules configuration is a great way to make common application utilities easily accessible throughout your application. We can emulate this same behavior in Jest using the moduleDirectories configuration option.

    For example:
    webpack.config.js:
    resolve: {
      modules: ['node_modules', 'shared']
    }

    What it does it in your shared folder, you exports some helper methods/ components, for example one is called CalculatorDisplay

    import CalculatorDisplay from 'calculator-display'

    Without resolve.modules, you have to to do:

    import CalculatorDisplay from ../../shared/'calculator-display', webpack made it easy for you.

    But Jest test will fail, you need to provide the same module resolver to Jest as well:

    const path = require('path')
    
    module.exports = {
      ...
      moduleDirectories: ['node_modules', 'shared'],
      ...
    }

    Run ESLint with Jest using jest-runner-eslint

    Jest is more than a testing framework. It’s a highly optimized, blazing fast platform with incredible parallelization for running tasks across many files in our project. It has a capability to run more than just tests. We can bring these features to our linting as well. Let’s see how we can bring our favorite Jest features (like watch mode) to ESLint with jest-runner-eslint.

    https://testingjavascript.com/lessons/jest-run-eslint-with-jest-using-jest-runner-eslint

    npm install --save-dev jest-runner-eslint

    Test Specific Projects in Jest Watch Mode with jest-watch-select-projects

    It’s great that we can run multiple projects in our watch mode and that we can scope the tests down to specific tests, but sometimes it’s nice to be able to quickly switch between projects in watch mode. Let’s see how this works with jest-watch-select-projects.

    https://testingjavascript.com/lessons/jest-test-specific-projects-in-jest-watch-mode-with-jest-watch-select-projects

    npm install --save-dev jest-watch-select-projects

    +

    Filter which Tests are Run with Typeahead Support in Jest Watch Mode

    Jest’s watch mode is pluggable and jest-watch-typeahead is one plugin that you definitely don’t want to live without. It enhances the watch mode experience to help you know which tests will be run based on your filter. Making it even easier to run only the tests you’re concerned with running as you develop your codebase.

    https://testingjavascript.com/lessons/jest-filter-which-tests-are-run-with-typeahead-support-in-jest-watch-mode 

    npm install --save-dev jest-watch-typeahead
    watchPlugins: [
      'jest-watch-select-projects',
      'jest-watch-typeahead/filename',
      'jest-watch-typeahead/testname',
    ]
  • 相关阅读:
    Reactor Cooling(无源汇有上下界网络流)
    费用流——消圈算法
    中间数(二分)+单调队列
    使用ServerSocket建立聊天服务器(二)
    使用ServerSocket建立聊天服务器(一)
    ServerSocket的建立和使用
    Socket介绍
    使用HttpClient进行Post通信
    使用HttpClient进行Get通信
    使用Post进行Http通信
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16792142.html
Copyright © 2020-2023  润新知