使用Mocha、Istanbul和Chai实现TypeScript单元测试和覆盖率

本文主要描述使用Mocha、Istanbul和Chai实现TypeScript单元测试和覆盖率的方法和过程,并简单记录SonarQube的相关配置。

Github: https://github.com/prufeng/tsexpress

关于JavaScript的单元测试和覆盖率,可参考:使用Mocha和Istanbul实现Node.js单元测试和覆盖率

Install

安装相关module和types。
Mocha是基本单元测试工具。
nyc用来统计代码覆盖率。
Chai则主要用来测试HTTP request。

npm i -D mocha
npm i -D nyc
npm i -D chai
npm i -D chai-http
npm i -D source-map-support

npm i -D @types/mocha
npm i -D @types/chai
npm i -D @types/chai-http

Mocha

mocha.opts

创建test/mocha.opts,配置如下。

--require ts-node/register
--require source-map-support/register
--recursive
--full-trace
--bail
test/**/*.spec.ts

app.spec.ts

创建test/app.spec.ts,添加以下test case测试当前的几个RESTful API。

import chai from 'chai';
import chaiHttp from 'chai-http';
import server from '../src/server';

let should = chai.should();
chai.use(chaiHttp);

describe('App Unit Test', () => {
    it('should get status 200', (done) => {
        chai.request(server)
            .get('/')
            .end((err, res) => {
                res.should.have.status(200);
                done();
            });
    });
    it('should get user list', (done) => {
        chai.request(server)
            .get('/users')
            .end((err, res) => {
                res.should.have.status(200);
                res.text.should.eql('respond with the user list here');
                done();
            });
    });
    it('should get status 404', (done) => {
        chai.request(server)
            .get('/wrongUrl2018')
            .end((err, res) => {
                res.should.have.status(404);
                // res.text.should.eql('respond with the user list here');
                done();
            });
    });
});

Unit Test

运行mocha命令,测试通过的结果如下。

mocha

  App Unit Test
GET / 200 13.293 ms - 198
    √ should get status 200
GET /users 200 0.662 ms - 31
    √ should get user list
GET /wrongUrl2018 404 7.099 ms - 1339
    √ should get status 404


  3 passing (55ms)

Istanbul(nyc)

package.json

修改package.json,增加nyc相关配置。
includeextesion包含需要测试的source code,reporter指明需要生成的report,缺省为text。

  "scripts": {
    "start": "npm run serve",
    "serve": "node dist/out-tsc/server",
    "test": "nyc mocha",
    "build":"tsc -p tsconfig.json"
  },
  "nyc": {
    "include": [
      "src/**/*.ts",
      "src/**/*.tsx"
    ],
    "exclude": [
      "**/*.d.ts"
    ],
    "extension": [
      ".ts",
      ".tsx"
    ],
    "require": [
      "ts-node/register"
    ],
    "reporter": [
      "text",
      "html"
    ],
    "sourceMap": true,
    "instrument": true,
    "all": true
  },

npm test

npm test实际上是运行nyc mocha,但直接运行nyc mocha得不到正确的结果,因为无法加载package.json里的nyc配置。
成功运行后参考结果如下。

--------------------|----------|----------|----------|----------|-------------------|
File                |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------------|----------|----------|----------|----------|-------------------|
All files           |    79.03 |    36.84 |    85.71 |    79.03 |                   |
 src                |       74 |    33.33 |    66.67 |       74 |                   |
  app.ts            |      100 |      100 |      100 |      100 |                   |
  server.ts         |    56.67 |    33.33 |    66.67 |    56.67 |... 70,72,73,74,76 |
 src/app/common     |      100 |       50 |      100 |      100 |                   |
  errHandler.ts     |      100 |       50 |      100 |      100 |               7,9 |
 src/app/demo       |      100 |      100 |      100 |      100 |                   |
  homeController.ts |      100 |      100 |      100 |      100 |                   |
  userController.ts |      100 |      100 |      100 |      100 |                   |
--------------------|----------|----------|----------|----------|-------------------|

如果生成了html report,可在coverage目录下打开index.html。html report的好处是可以点击查看每个文件的具体测试覆盖详情。
在这里插入图片描述

SonarQube

Install SonarQube Plugin - SonarTS

https://docs.sonarqube.org/display/PLUG/SonarTS

sonar.properties

sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.typescript.lcov.reportPaths=coverage/lcov.info

(Works without sonar.typescript.lcov.reportPaths configure from my test. )

Reference

https://istanbul.js.org/docs/tutorials/typescript/

在这里插入图片描述

单元测试Unit Tests)和集成测试(Integration Tests)是软件开发中的两种关键测试策略: **单元测试 (unit tests):** - 单元测试是在最小可测试单元(通常是函数或方法)级别上进行的测试。在`unitTests`目录下,你可能会创建一个针对每个核心功能或模块的单独测试文件,比如`mathUtils.test.js`或`databaseHandler.test.js`。 - 使用工具如Mocha(JavaScript)或JUnit(Java),配合断言库如Chai、Jest或JUnit assertions,对代码的各个部分进行细致的验证,确保它们按预期工作,独立于其他组件。 - 示例代码片段(假设使用MochaChai): ```javascript const assert = require('chai').assert; describe('MathUtils.add', function() { it('should add two numbers correctly', function() { const result = MathUtils.add(2, 3); assert.equal(result, 5); }); }); ``` **集成测试 (integration tests):** - 集成测试则关注组件之间的交互,验证整个系统是如何协同工作的。这可能涉及到多个模块和服务的组合,例如API端点与数据库的交互。 - 在`integrationTests`目录下的文件通常会模拟或设置外部依赖,然后测试如何从用户接口角度触发这些内部交互。 - 例如,在Express应用中,可能测试`usersController`和`databaseAdapter`如何一起处理用户注册请求: ```javascript const request = require('supertest'); describe('User registration API', function() { it('should create a new user and save to the database', async () => { const res = await request(app) .post('/api/users') .send({ username: 'test', password: 'password' }); assert.equal(res.status, 201); const savedUser = await UserService.getUserById(res.body.id); assert.isNotNull(savedUser); }); }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值