消消乐系列--单元测试

it2025-11-06  12

在 TypeScript 开发中,需要为开发的模块编写单元测试,参考使用 jest 这个框架。https://www.jestjs.cn

安装部署

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 文件中:

//更多信息关注微信公众号

在使用过程中有什么问题,或者有什么BUG亦或有什么新的需求都可以留言。能解决的会抽时间进行解决。

谢谢大家的支持

长按下图二维码关注,你将感受到一个渴望成长的灵魂,且每篇文章都有惊喜。

最新回复(0)