【Express.js】软件测试

软件测试

本节介绍如何在 express.js 使用 Jest 进行单元测试

准备工作

  1. 准备一个基础的 express 项目,本文基于 evp-express-cli
  2. 安装 Jest
npm install jest --save-dev
  1. 生成 Jest 配置
npx jest --init

编写测试

创建测试文件,以 .test.js 后缀命名,Jest 在运行期间会自动查找并执行符合 *.test.js 命名的文件,为规范起见,新建一个 test 目录,存放所有的测试文件。

编写第一个测试

  1. 先准备一个要被测试的函数 sum(a, b),写在 src/uitls/index.js 中:
module.exports = {
  /**
   * Return the result of the sum of a and b.
   * @function
   * @param {number} a 
   * @param {number} b 
   * @returns {number}
   */
  sum: (a, b) => {
    return a + b;
  }
}
  1. test 目录下创建 sum.test.js,引入 sum 并编写测试代码:
const { sum } = require('../src/utils');

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

toBe() 可以简单得判断相等,类似于 assertEqual,Jest 的具体语法本文不做介绍,自行查阅,其它测试框架如 mocha.js 的语法也是类似的。
3. 执行测试

npx jest

得到结果:

 PASS  test/sum.test.js
  test demo
    √ sum test (2 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 | 
 index.js |     100 |      100 |     100 |     100 | 
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.58 s, estimated 1 s

对路由进行测试

现在我们尝试对路由进行测试,先安装 supertest

npm install supertest --save-dev

test 目录创建 router.test.js,引入 express app 和 supertest:

const request = require('supertest');
const app = require('../src/app');

接着争对 src/router/index.js 中定义的 / 路由进行测试:

describe('router test', () => {
  it('GET /', () => {
    request(app).get('/')
    .expect('Content-Type', /json/)
    .expect(200)
    .then(res => {
      expect(res.body).toStrictEqual({
        ok: true, 
        msg: 'Hello World!', 
        data: null, 
        symbol: 1, 
        type: 'Ok' 
      });
    }).catch(err => console.error(err));
  })
})

toStrictEqual 用于判断对象的严格相等;对路由测试需要用到 supertest 传入 app,然后对其 / 路由发起 GET 请求,因为请求过程是异步的,所以对响应结果的测试写在 then 回调中,当然你也可以把测试函数写成 async-await 语法糖;这个路由不需要传递任何数据,如果你需要携带数据,可以使用 send (x-www-form-urlencoded), set (请求头), field (multipart-form)等,具体用法请自行查阅 supertest 文档。

接下来执行测试:

npx jest

得到结果:

 PASS  test/sum.test.js   
 PASS  test/router.test.js
---------------|---------|----------|---------|---------|------------------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|------------------------------
All files      |   62.93 |       60 |      30 |   62.93 |                              
 src           |   71.76 |    66.66 |     100 |   71.76 |                              
  app.js       |     100 |      100 |     100 |     100 |                              
  config.js    |   66.66 |    66.66 |     100 |   66.66 | 36-59                        
 src/midwares  |   30.18 |      100 |       0 |   30.18 | 
  exhandler.js |   30.18 |      100 |       0 |   30.18 | 7-12,16-22,26-43,47-52      
 src/model     |      50 |        0 |       0 |      50 | 
  resp.js      |      50 |        0 |       0 |      50 | 4-10,19-25,29-31,35-37,41-43
 src/router    |   83.33 |      100 |     100 |   83.33 | 
  index.js     |   83.33 |      100 |     100 |   83.33 | 8-9
 src/utils     |     100 |      100 |     100 |     100 | 
  index.js     |     100 |      100 |     100 |     100 | 
  logger.js    |     100 |      100 |     100 |     100 | 
---------------|---------|----------|---------|---------|------------------------------

Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        2.054 s
Ran all test suites.
[2023-08-06 18:43:20] INFO Hello World!

如果你只想执行 router.test.js,则在后边指定要执行的测试文件即可:

npx jest test/router.test.js

下一节-软件构建

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值