
在 TypeScript 开发中,需要为开发的模块编写单元测试,参考使用 jest 这个框架。
npm install -D jest ts-jest @types/jest npm install -D jest-canvas-mock npm install typescript
配置jest
package.json
{ "name": "cocos creator", "version": "1.0.0", "description": "使用cocos creator 编写的三消游戏。", "scripts": { "test-single": "npx jest --silent --verbose", "test-all": "npx jest --silent --coverage" }, "jest": { "testEnvironment": "node" }, "dependencies": { "jest-canvas-mock": "^2.3.0", "typescript": "^4.0.3" }, "devDependencies": { "@types/jest": "^26.0.15", "jest": "^26.6.0", "ts-jest": "^26.4.1" } }
编写 test 用例
jest.config.js
module.exports = { roots: [ "<rootDir>/test" ], preset: "ts-jest", setupFiles: ["jest-canvas-mock",], collectCoverageFrom: ["assets/script/ui/match3/core/**/*.ts"], };
编写单元测试代码
import { EMRandom } from "../assets/script/ui/match3/core/EMRandom"; const random = new EMRandom(123); describe("test EMRandom" , () => { test('#nextInt', () => { expect(random.nextInt(6)).toBe(3); }); test('#next', () => { expect(random.next(6)).toBe(8); }); });
执行 npm run test-single
即可运行测试用例。
执行 npm run test-all
即可运行测试覆盖率报告。
VSCode 调试
我们如果在 VSCode 环境下,需要调试用例,则可以进行如下配置,在 .vscode/launch.json 文件中:
{ "version": "1.4.0", "configurations": [ { "name": "Creator Debug: Launch Chrome", "type": "chrome", "request": "launch", "url": "http://localhost:7456", "sourceMaps": true, "userDataDir": "${workspaceFolder}/.vscode/chrome", "diagnosticLogging": false, "pathMapping": { "/preview-scripts/assets": "${workspaceFolder}/temp/quick-scripts/dst/assets", "/": "${workspaceFolder}" } }, { "type": "node", "request": "launch", "name": "Jest Coverage", "program": "${workspaceFolder}/node_modules/.bin/jest", "args": ["--silent","--coverage"], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "disableOptimisticBPs": true, "windows": { "program": "${workspaceFolder}/node_modules/jest/bin/jest", } }, { "type": "node", "request": "launch", "name": "Jest Verbose", "program": "${workspaceFolder}/node_modules/.bin/jest", "args": ["--silent","--verbose"], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "disableOptimisticBPs": true, "windows": { "program": "${workspaceFolder}/node_modules/jest/bin/jest", } }, ] }