Cocos Creator用jtest单元测试攻略极速版

主要参考了CocosCreator 中单元测试入门,但是该文代码在我电脑上并没有正常执行,所以修正后写了本文。毕竟,一篇攻略,最基本的要求应该是,可以成功运作
想要了解到底是为什么每一步要那么做的,可以阅读原文。

注意

用本测试框架测试有个问题,不能测试引入cocos creator的API的方法。

这些方法的测试需要引擎的介入,所以不在本文讨论范围内。

安装ts-jest

npm install --save-dev ts-jest

测试ts-jest

安装好之后,测试一下。

修改根目录的package.json,加上

{
    "scripts": {
        "test": "jest"
    }
}

执行命令npm test或者npm t,应该会发现执行成功,但是没有单元测试用例

增加测试配置

在根目录新建文件jest.config.js,内容为

module.exports = {
    preset: "ts-jest",        
    testEnvironment: 'node', 
    rootDir: "./tests",   // 测试文件所在的目录
    globals: {            // 全局属性。如果你的被测试的代码中有使用、定义全局变量,那你应该在这里定义全局属性
        window: {},       
        cc: {}
    }
};

增加单元测试用例

增加用于测试的方法

我们在CocosCreator项目自带的assets目录下新建文件playground.ts,内容为

export function add(a: number, b: number): number {
  return a + b;
}

增加测试用例

随后在项目根目录新建tests文件夹,在其中新建文件playground.test.ts,内容为

import {readableNum} from '../assets/playground';
import {expect, test} from '@jest/globals';

test('add', () => {
  expect(add(1, 2)).toBe(3);
});

配置tsconfig

执行命令npm test或者npm t,会发现如下报错,照着做就好了

ts-jest[config] (WARN) message TS151001: If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.

在根目录的tsconfig.json里修改

{
    /* Base configuration. Do not edit this field. */
    "extends": "./temp/tsconfig.cocos.json",
    /* Add your custom configuration here. */
    "compilerOptions": {
        "strict": false,
        "esModuleInterop": true
    }
}

即增加了esModuleInterop配置

执行成功

这时候,如果在Webstorm里,就能看到test('add'xxx这一行左边的小箭头了,直接点击就可以运行。

咱们可以执行下面的命令执行一下所有测试用例

npm test
posted @ 2022-09-27 18:59  亚楠老猎人  阅读(470)  评论(0编辑  收藏  举报