单元测试
¥Unit testing
Strapi 博客上有一个关于如何实现 使用 Jest 和 Supertest 进行 API 测试 和 如何将单元测试添加到你的 Strapi 插件 的教程。
¥The Strapi blog has a tutorial on how to implement API testing with Jest and Supertest and how to add unit tests to your Strapi plugin .
在本指南中,我们将了解如何使用测试框架为 Strapi 应用运行基本单元测试。
¥In this guide we will see how you can run basic unit tests for a Strapi application using a testing framework.
在此示例中,我们将使用 Jest 测试框架,重点关注简单性,并使用 超测 超级代理驱动库,使用流畅的 API 测试 node.js HTTP 服务器。
¥In this example we will use Jest Testing Framework with a focus on simplicity and Supertest Super-agent driven library for testing node.js HTTP servers using a fluent API.
请注意,如果你在 Windows 上 使用 SQLite 数据库,由于 Windows 锁定 SQLite 文件的方式,本指南将不起作用。
¥Please note that this guide will not work if you are on Windows using the SQLite database due to how windows locks the SQLite file.
安装测试工具
¥Install test tools
Jest
包含一组用于创建和设计测试用例的指南或规则 - 旨在帮助测试人员更有效地进行测试的实践和工具的组合。
¥Jest
contains a set of guidelines or rules used for creating and designing test cases - a combination of practices and tools that are designed to help testers test more efficiently.
Supertest
允许你测试所有 api
路由,因为它们是 http.Server 的实例。
¥Supertest
allows you to test all the api
routes as they were instances of http.Server .
sqlite3
用于创建在测试之间创建和删除的磁盘数据库。
¥sqlite3
is used to create an on-disk database that is created and deleted between tests.
- yarn
- npm
yarn add --dev jest supertest sqlite3
npm install jest supertest sqlite3 --save-dev
完成后将其添加到 package.json
文件中
¥Once this is done add this to package.json
file
将 test
命令添加到 scripts
部分
¥add test
command to scripts
section
"scripts": {
"develop": "strapi develop",
"start": "strapi start",
"build": "strapi build",
"strapi": "strapi",
"test": "jest --forceExit --detectOpenHandles"
},
并在文件底部添加这些行
¥and add those lines at the bottom of file
"jest": {
"testPathIgnorePatterns": [
"/node_modules/",
".tmp",
".cache"
],
"testEnvironment": "node"
}
这些将通知 Jest
不要在不应查找的文件夹内查找测试。
¥Those will inform Jest
not to look for test inside the folder where it shouldn't.