官方例子编写单元测试:
// extend/helper.js
'use strict';
module.exports = {
  money(val) {
    const lang = this.ctx.get('Accept-Language');
    if (lang.includes('zh-CN')) {
      return `¥ ${val}`;
    }
    return `$ ${val}`;
  },
};
//test/app/extend/helper.test.js
'use strict';
const { app, assert } = require('egg-mock/bootstrap');
describe('money()', () => {
  it('should RMB', () => {
    const ctx = app.mockContext({
      // 模拟 ctx 的 headers
      headers: {
        'Accept-Language': 'zh-CN,zh;q=0.5',
      },
    });
    assert(ctx.helper.money(100) === '¥ 100');
  });
  it('should US Dolar', () => {
    const ctx = app.mockContext();
    assert(ctx.helper.money(100) === '$ 100');
  });
});
运行 egg-bin test --watch  测试通过;
修改 test/app/extend/helper.test.js 文件,去掉 '¥',测试自动运行,should RMB 不通过;
恢复 test/app/extend/helper.test.js 文件,测试全部通过,然后修改 extend/helper.js 文件 去掉 '¥' ,测试自动运行。理论上should RMB会失败,但实际测试依然通过。也就是说 修改 extend/helper.js 文件之后,测试运行的不是最新的helper.js,一直运行的是启动 egg-bin test --watch 命令时的 helper.js;
- 操作系统:macOS 10.13.4
- Node 版本:v12.14.0
- Egg 版本:2.27.0