[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',
]

 

 

 

posted @   Zhentiw  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-10-18 [Kotlin Unit test] Spek & Mock
2019-10-18 [Flutter & Dart] Await a Future void function
2017-10-18 [AngularFire] Resolve snapshotChanges doesn't emit value when data is empty
2016-10-18 [CSS] Use CSS Counters to Create Pure CSS Dynamic Lists
2016-10-18 [CSS] Target empty elements using the :empty pseudo-class
2016-10-18 [Angular2 Animation] Basic animation
2016-10-18 [Angular2 Router] Auxiliary Routes bit by bit
点击右上角即可分享
微信分享提示