How to test JavaScript applications with Jest
我们知道,Jest 是 FaceBook 用来测试 JavaScript 应用的一套测试框架,那么也包含了一些应用,它的优点其中就包括了对于React 的支持,也很容易支持其他框架,那么今天我们就教大家怎么用Jest测试JS应用
从最简单的开始,我们可以看看如何用 Jest 测试纯 JS 项目。
假设你需要测试 sum.js:
export default (a, b) => a + b
你只需要对应地新建一个 sum.test.js[1]:
import sum from './sum' test('sum', () => { expect(sum(2, 3)).toBe(5) })
关于这里的 `expect` 语法
然后在终端运行 jest 命令的时候就会自动找到这个文件,执行这里面的测试:
额,报错了,原来 Jest 默认只支持你所使用的 node.js 版本所支持的 JS 特性,例如 import export 就不支持,所以要么你的代码使用系统 node.js 兼容的语法写 (也就是使用 require),要么在这里使用 Babel 转义一下。
在 Jest 中使用 Babel 很简单,只需要安装 babel-jest 并新建一个 .babelrc 加入你想要的配置就行了,Jest 会自动使用 babel-jest。这里我们简单地使用 babel-preset-env 即可,对应的 .babelrc 是:
{ "presets": ["env"] }
然后重新运行 jest 测试便通过了:
jest 2
对于 React 应用,基本和纯 JS 项目类似,不过你需要在 .babelrc 中配置对 JSX 的支持,在大多数时候你的项目本身就已经在使用 .babelrc 了,所以这一步甚至也省略掉了。
资源文件
当你要测试的代码引用了非 JS 文件时,Jest 就不知道如何使用这些文件了,例如你的 Webpack 项目中的一个文件:
import './style.css'
正如你需要在 Webpack 中配置了 css-loader 一样,你也需告诉 Jest 如何处理 CSS 文件。
{ "jest": { "transform": { "^.+\\.(js|jsx)$": "babel-jest", "^.+\\.css$": "<rootDir>/jest/css-transform.js" } } } 关于 babel-jest 对应的 ./jest/css-transform.js // 大多数测试并不关心 CSS 文件里的内容 // 所以这里我们直接返回一个空的对象 module.exports = { process() { return 'module.exports = {};' }, getCacheKey() { // The output is always the same. return 'css-cache' } }
类似地,你可以使用 transform 来设定如何处理其它类型的文件,比如 .vue[2] .svg 文件。
浏览器 API
假设你要测试的是一个 Web 应用,依赖于一些浏览器 API 比如 window document,它在 Jest 中同样可以正常运行,因为 Jest 默认使用了 js-dom 来模拟浏览器环境,不需要浏览器环境时可以通过使用命令行参数 --env node 或者配置文件来禁用。
Snapshot 测试
当你期望某个值不会改变的时候,可以使用 snapshot 测试。简单地说,它就是记录这个值的状态到本地自动生成的 snapshot 文件里,然后在下一次测试中用新的值来和其进行对比。这对 UI 之类的测试很有帮助:
import React from 'react' import Link from '../Link.react' import renderer from 'react-test-renderer' it('renders correctly', () => { const tree = renderer .create(<Link page="http://www.facebook.com">Facebook</Link>) .toJSON() expect(tree).toMatchSnapshot() })
这确保了 Facebook 渲染出的内容不会出错。
当你更改了 组件的逻辑,需要更新 snapshot 文件时,可以加上 --updateSnapshot 或者 -u 来更新。
类似的,Snapshot 测试不止于 UI 测试中,假设你写了个 Markdown 解析器,你可以用它来确保解析出的内容不会改变:
import renderMarkdown from './my-markdown-parser' test('render correctly', () => { const html = renderMarkdown('# markdown code') expect(html).toMatchSnapshot() })
相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
相关阅读:
The above is the detailed content of How to test JavaScript applications with Jest. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Deleted something important from your home screen and trying to get it back? You can put app icons back on the screen in a variety of ways. We have discussed all the methods you can follow and put the app icon back on the home screen. How to Undo Remove from Home Screen in iPhone As we mentioned before, there are several ways to restore this change on iPhone. Method 1 – Replace App Icon in App Library You can place an app icon on your home screen directly from the App Library. Step 1 – Swipe sideways to find all apps in the app library. Step 2 – Find the app icon you deleted earlier. Step 3 – Simply drag the app icon from the main library to the correct location on the home screen. This is the application diagram

The role and practical application of arrow symbols in PHP In PHP, the arrow symbol (->) is usually used to access the properties and methods of objects. Objects are one of the basic concepts of object-oriented programming (OOP) in PHP. In actual development, arrow symbols play an important role in operating objects. This article will introduce the role and practical application of arrow symbols, and provide specific code examples to help readers better understand. 1. The role of the arrow symbol to access the properties of an object. The arrow symbol can be used to access the properties of an object. When we instantiate a pair

The Linuxtee command is a very useful command line tool that can write output to a file or send output to another command without affecting existing output. In this article, we will explore in depth the various application scenarios of the Linuxtee command, from entry to proficiency. 1. Basic usage First, let’s take a look at the basic usage of the tee command. The syntax of tee command is as follows: tee[OPTION]...[FILE]...This command will read data from standard input and save the data to

The Go language is an open source programming language developed by Google and first released in 2007. It is designed to be a simple, easy-to-learn, efficient, and highly concurrency language, and is favored by more and more developers. This article will explore the advantages of Go language, introduce some application scenarios suitable for Go language, and give specific code examples. Advantages: Strong concurrency: Go language has built-in support for lightweight threads-goroutine, which can easily implement concurrent programming. Goroutin can be started by using the go keyword

The wide application of Linux in the field of cloud computing With the continuous development and popularization of cloud computing technology, Linux, as an open source operating system, plays an important role in the field of cloud computing. Due to its stability, security and flexibility, Linux systems are widely used in various cloud computing platforms and services, providing a solid foundation for the development of cloud computing technology. This article will introduce the wide range of applications of Linux in the field of cloud computing and give specific code examples. 1. Application virtualization technology of Linux in cloud computing platform Virtualization technology

MySQL timestamp is a very important data type, which can store date, time or date plus time. In the actual development process, rational use of timestamps can improve the efficiency of database operations and facilitate time-related queries and calculations. This article will discuss the functions, features, and application scenarios of MySQL timestamps, and explain them with specific code examples. 1. Functions and characteristics of MySQL timestamps There are two types of timestamps in MySQL, one is TIMESTAMP

1. First we click on the little white dot. 2. Click the device. 3. Click More. 4. Click Application Switcher. 5. Just close the application background.

Golang is an open source programming language developed by Google that has many unique features in concurrent programming and memory management. Among them, Golang's stack management mechanism is an important feature. This article will focus on the mechanism and application of Golang's stack management, and give specific code examples. 1. Stack management in Golang In Golang, each goroutine has its own stack. The stack is used to store information such as parameters, local variables, and function return addresses of function calls.
