Node egg.js mock单元测试学习1

说明:

自己是根据官网学习,可能自己话术并不好,也推荐大家先去官网学习

生成项目

//通过脚手架生成项目
$ egg-init egg_mock_demo --type=simple

....
[egg-init] usage:
      - cd /Users/zhujiawei/egg/egg_mocha_demo
      - npm install
      - npm start / npm run dev / npm test
//执行npm i

可以发现 让我运行npm test,说明脚手架的项目已经有了单元测试的案例,虽然还不懂也执行一下看看

> egg-bin test



  test/app/controller/home.test.js
    ✓ should assert
    ✓ should GET /


  2 passing (669ms)

测试目录结构

为了让我们更多地关注测试用例本身如何编写,而不是耗费时间在如何运行测试脚本等辅助工作上,框架对单元测试做了一些基本约定
test
├── app
└── controller
└── home.test.js

Controller 测试




以下两个方法是对controller层以及router层的测试,
会访问/ 并跳转到对应的controller层 最后返回结果
describe('test/app/controller/home.test.js', () => {

  it('should GET /', () => {
    return app.httpRequest()
    	//访问 get / 
      .get('/')
      	//希望返回的结果
      .expect('hi, egg')
      	//希望返回的状态 
      .expect(200);
  });

// 使用generator function 方式写测试用例,可以在一个用例中串行发起多次请求
  it('should send multi requests', async () => {
    await app.httpRequest()
      .get('/')
      .expect('hi, egg')
      .expect(200);

    // 在请求一次
    const result = await app.httpRequest()
      .get('/')
      .expect(200)
      .expect('hi, egg');


    assert(result.status === 200);
  });
});

执行npm test

> egg_mocha_demo@1.0.0 test /Users/zhujiawei/egg/egg_mocha_demo
> npm run lint -- --fix && npm run test-local


> egg_mocha_demo@1.0.0 lint /Users/zhujiawei/egg/egg_mocha_demo
> eslint . "--fix"


> egg_mocha_demo@1.0.0 test-local /Users/zhujiawei/egg/egg_mocha_demo
> egg-bin test



  test/app/controller/home.test.js
    ✓ should GET /
    ✓ should send multi requests


  2 passing (672ms)

测试没有出什么问题

service 测试

service 相对于Controller来水,测试起来会更加简单,我们只需要先创建一个ctx,然后通过
ctx.service.${serviceName}拿到service实例,然后调用Service方法即可

  • 编写service层
'use strict';

const Service = require('egg').Service;

class UserService extends Service {
  async get(name) {
    return name;
  }
}

module.exports = UserService;
  • 编写test
test/app/service/user.test.js
'use strict';
const { app, assert } = require('egg-mock/bootstrap');
describe('get()', () => {
  it('should get exists user', async () => {
    // 创建 ctx
    const ctx = app.mockContext();
    // 通过 ctx 访问到 service.user
    const user = await ctx.service.user.get('fengmk2');
    assert(user === 'fengmk2');
  });
});
  • 执行npm test
 test/app/controller/home.test.js
    ✓ should GET /
    ✓ should send multi requests

  get()
    ✓ should get exists user

成功~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值