@yunflyjs/yunfly-unit-test
TypeScript icon, indicating that this package has built-in type declarations

0.0.1 • Public • Published

单元测试

说明

  • 使用jest测试框架 文档地址;
  • 使用supertest进行接口模拟请求 文档地址;
  • 单元测试目录为 根目录/src/__test__,单元测试文件为 .test.ts (可进行自定义配置);
  • @yunflyjs/yunfly-unit-test 只支持 yunfly 的项目;

使用

  1. 安装依赖
yarn add @yunflyjs/yunfly-unit-test --dev
  1. 项目根目录下新增jest.config.js文件,内容如下:
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  roots: ["<rootDir>/src/__test__"],
  verbose: true,
};
    1. package.json 新增 test 脚本命令
"scripts": {
  "test": "jest -runInBand --forceExit --colors"
}

测试案例

简单案例

// example.ts
export function sum(a:any, b:any) {
  return a + b;
}
  • 单词用例
// title="src/__test__/http.simple.ts"
import { sum } from '../example.ts';

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

更多能力请参考 jest

测试接口案例

  • controller
import { Get, JsonController, BodyParam, Post, QueryParam } from '@yunflyjs/yunfly';

@JsonController('/example')
export default class ExampleController {

  @Get('/simple/get')
  async simple(
    @QueryParam('name') name: string,
  ): Promise<any> {
    return {
      name:name || 'success'
    };
  }
  
  @Post('/simple/post')
  simple1(
    @BodyParam('name') name: string,
  ): any {
    return {
      name:name || 'success'
    };
  }
}
  • 单测用例

  • get

// src/__test__/http.get.ts
import { request } from '@yunflyjs/yunfly-unit-test'

test('GET /example/simple/get', async () => {
  const res = await request.get('/example/simple/get');
  expect(res.body).toEqual({ "name": "success" });
});
  • post
// src/__test__/http.test.ts
import { request } from '@yunflyjs/yunfly-unit-test'

describe('POST /example/simple/post', function() {
  test('test default response', async () => {
    const res = await request
      .post('/example/simple/post')
      .set('Accept', 'application/json');
      expect(res.body.name).toEqual('success');
  });

  test('test request params', async () => {
    const res = await request
      .post('/example/simple/post')
      .send({name: 'john'})
      .set('Accept', 'application/json');
  
      expect(res.status).toEqual(200);
      expect(res.body.name).toEqual('john');
  });
})

request api 请参考 supertest

Package Sidebar

Install

npm i @yunflyjs/yunfly-unit-test

Weekly Downloads

4

Version

0.0.1

License

MIT

Unpacked Size

9.61 kB

Total Files

6

Last publish

Collaborators

  • wangweianger