egg如何写单元测试

优秀的代码需要有单元测试进行质量保证,每个测试用例都给应用的稳定性提供了一层保障。

测试目录结构

我们约定 test 目录为存放所有测试脚本的目录,测试所使用到的 fixtures 和相关辅助脚本都应该放在此目录下。

测试文件的目录和我们需要测试的文件目录必须保持一直

测试脚本文件统一按 ${filename}.test.js 命名,必须以 .test.js 作为文件后缀。 一个应用的测试目录示例:

javascript 复制代码
test
├── controller
│   └── home.test.js
└── service
  └── user.test.js

测试运行工具

统一使用 egg-bin 来运行测试脚本, 自动将内置的 Mocha、co-mocha、power-assert,nyc 等模块组合引入到测试脚本中, 让我们聚焦精力在编写测试代码上,而不是纠结选择那些测试周边工具和模块。

javascript 复制代码
"scripts": {
    "test": "egg-bin test",
    "cov": "egg-bin cov"
}

egg单元测试

Egg框架规定,所有的测试代码,都需要放在/test目录下面。如果是Controller相关的代码就需要放在/test/app/controller文件夹下面。所有的测试文件都需要以.test.js为后缀的。

首先我们看下router.js中的接口

javascript 复制代码
  // HOT
  router.get('/api/hots', controller.hot.findHots); // 获取所有热门资讯
  router.post('/api/hots', controller.hot.addHot); // 添加热门资讯
  router.put('/api/hots/:id', controller.hot.editHot); // 编辑热门资讯
  router.delete('/api/hots/:id', controller.hot.delHot); // 删除热门资讯

然后创建一个hot.test.js文件,编写下面的测试文件。

javascript 复制代码
'use strict';

const { app } = require('egg-mock/bootstrap');

describe('test/app/controller/hot.test.js', () => {
  it('should GET /api/hots', () => {
    return app.httpRequest()
      .get('/api/hots') // GET 请求
      .expect(200);
  });
  it('should POST /api/hots', async () => {
    return app.httpRequest()
      .post('/api/hots')
      .send({
        title: '第一个热门资讯',
        description: '今天青岛做网站在使用MySQL数据库做项目时突然遇到提交数据提示Field xxx doesn't have a default value这个错误',
        linkUrl: '/about/news/1289',
        sort: 4,
      })
      .expect(200);
  });
  it('should PUT /api/hots/:id', async () => {
    return app.httpRequest()
      .put('/api/hots/:id')
      .send({
        id: 7,
        title: '第一个热门资讯',
        description: '今天青岛做网站在使用MySQL数据库做项目时突然遇到提交数据提示Field xxx doesn't have a default value这个错误',
        linkUrl: '/about/news/1289',
        sort: 4,
      })
      .expect(200);
  });
  it('should DELETE /api/hots/:id', async () => {
    return app.httpRequest()
      .delete('/api/hots/:id')
      .send({
        id: 7,
      })
      .expect(200);
  });
});

执行npm test,就可以开启测试了。

相关推荐
胡利光12 小时前
Harness Engineering 02|Repo Harness:让仓库对 Agent 可读
java·junit·单元测试
Elastic 中国社区官方博客13 小时前
使用 EDOT Browser 和 Kibana 进行 OpenTelemetry 浏览器端埋点
大数据·服务器·数据库·elasticsearch·搜索引擎·单元测试·可用性测试
姚青&1 天前
软件测试基础概念
单元测试·pytest
川石课堂软件测试2 天前
技术分享|JMeter接口与性能测试实战
数据库·功能测试·测试工具·jmeter·单元测试·postman·prometheus
回忆2012初秋2 天前
.NET 时序数据操作实战:Apache IoTDB连接与 CRUD 完全指南
.net·apache·iotdb
weixin_430750932 天前
部署FreeRadius+php+apache+mariaDB+daloradius 实现认证计费功能
php·apache·mariadb·daloradius·freeradius
还在忙碌的吴小二3 天前
Apache HertzBeat 安装使用完整指南
apache
web前端神器3 天前
记录uniapp小程序的报错
小程序·uni-app·apache
汽车仪器仪表相关领域3 天前
Kvaser Leaf Light HS v2 CB:裸卡式CAN接口新标杆,赋能车载与工业集成测试高效升级
服务器·网络·数据库·人工智能·单元测试·自动化·汽车
川石课堂软件测试3 天前
软件测试:典型面试题库
数据库·python·功能测试·mysql·单元测试·grafana·prometheus