Egg.js 單元測試入門

官方推薦測試框架:MochaMocha中文網

官方推薦斷言庫:power-assert

Egg.js 中已經內置 Mochaco-mochapower-assertnyc 等模塊,只需要在 package.json 上配置好 scripts.test 即可。

{
  "scripts": {
    "test": "egg-bin test"
  }
}

運行測試:

npm test

注意: npm test 會首先進行 eslint 檢查,若有 error 則不會開始測試。

指定文件路徑,可以對某一個單元測試文件進行測試:

npm test ./path/to/user.test.js

目錄結構

約定 test 目錄爲存放所有測試腳本的目錄。

測試腳本文件統一按 ${filename}.test.js 命名,必須以 .test.js 作爲文件後綴。

test
├── controller
│   └── home.test.js
├── hello.test.js
└── service
    └── user.test.js

Controller 測試

describeit 的第一個字段都只是描述,每一個 it 是一個測試用例。

'use strict';

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

describe('test/app/controller/home.test.js', () => {
  it('should assert', () => {
    const pkg = require('../../../package.json');
    assert(app.config.keys.startsWith(pkg.name));

    // const ctx = app.mockContext({});
    // yield ctx.service.xx();
  });

  it('should GET /', () => {
    return app.httpRequest()
      .get('/')
      .expect(200) // 期望返回的 status 200
      .expect('hi, egg'); // 期望返回的 body,支持 string/
  });
});

describe('test/app/controller/user.test.js', () => {
  it('should POST /users', () => {
    return app.httpRequest()
      .post('/users')
      .send({ username: 'Mike', password: '123456' }) // post body
      .expect(200)
      .then(response => {
        // response.text 是返回的 body 字符串,轉成 json 後再通過 assert 校驗
        const res = JSON.parse(response.text);
        assert.equal(res.code, '0000'); // 業務錯誤碼應該爲'0000',字符串對比
        assert(res.data.userId); // userId應該存在,注意 0、false、空字符串 都會被判定爲失敗,與 assert.ok() 等效
      });
  });
});

前置和後置步驟

Mocha 使用 before/after/beforeEach/afterEach 來處理前置後置任務,基本能處理所有問題。 每個用例會按 before -> beforeEach -> it -> afterEach -> after 的順序執行,而且可以定義多個。

describe('egg test', () => {
  // Mocha 剛開始運行的時候會載入所有用例,這時調用 describe 方法,執行 before()
  before(() => console.log('order 1')); // 在當前 describe 中的所有用例之前執行
  before(() => console.log('order 2')); // 支持多個 before 函數
  after(() => console.log('order 6')); // 在當前 describe 中的所有用例之後執行
  beforeEach(() => console.log('order 3')); // 在當前 describe 中的每個用例之前執行
  afterEach(() => console.log('order 5')); // 在當前 describe 中的每個用例之後執行
  it('should worker', () => console.log('order 4'));
});

Service 測試

也可以直接對 Service 層進行測試。

describe('get()', () => {
  it('should get exists user', async () => {
    // 創建 ctx
    const ctx = app.mockContext();
    // 通過 ctx 訪問到 service.user
    const user = await ctx.service.user.get('admin');
    assert(user);
    assert(user.name === '管理員');
  });

  it('should get null when user not exists', async () => {
    const ctx = app.mockContext();
    const user = await ctx.service.user.get('admin');
    assert(!user);
  });
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章