我们知道,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!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools