如何使用从控制器返回的值?在NestJs上测试控制器

时间:2019-09-27 13:55:03

标签: node.js unit-testing testing nestjs sequelize-typescript

控制器和测试方法:

import { Controller, Get, Response, HttpStatus, Param, Body, Post, Request, Patch, Delete, Res } from '@nestjs/common';
@Controller('api/parts')
export class PartController {
  constructor(private readonly partsService: partsService) { }

  @Get()
  public async getParts(@Response() res: any) {
    const parts = await this.partsService.findAll();
    return res.status(HttpStatus.OK).json(parts);
  }
}

这是单元测试,必须测试getParts方法:

describe('PartsController', () => {
  let partsController: PartsController;
  let partsService: partsService;

  beforeEach(async () => {
    partsService = new partsService(Part);
    partsController= new PartsController(partsService);
  });

  describe('findAll', () => {
    it('should return an array of parts', async () => {
      const result = [{ name: 'TestPart' }] as Part[];

      jest.spyOn(partsService, 'findAll').mockImplementation(async () => result);

      const response = {
        json: (body?: any) => {
          expect(body).toBe(result);
        },
        status: (code: number) => response,
      };

      await partsController.getParts(response);
    });
  });
});

此测试正常运行,但是我认为这是一个不好的解决方案。当我调查此问题时,我看到了以下选项:

const response = {
  json: (body?: any) => {},
  status: (code: number) => response,
};
expect(await partsController.getParts(response)).toBe(result);

但是当我尝试它时,我的测试无法正常工作,导致等待partsController.getParts(response)//未定义 那我该怎么做才能使测试看起来更好呢?

在解决方案中,我使用:nodeJS sequelize,nestJS,打字稿

1 个答案:

答案 0 :(得分:0)

好的,我想您的问题出在实例化和使用控制器与服务的方式上。
NestJs Testing utils为您完成这项工作,就像这样:

describe('Parts Controller', () => {
    let partsController: PartsController;
    let partsService: PartsService;

    beforeEach(async () => {
        // magic happens with the following line
        const module = await Test.createTestingModule({
            controllers: [
                PartsController
            ],
            providers: [
                PartsService
                //... any other needed import goes here
            ]
        }).compile();

        partsService = module.get<PartsService>(PartsService);
        partsController = module.get<PartsController>(PartsController);
    });

    // The next 4 lines are optional and depends on whether you would need to perform these cleanings of the mocks or not after each tests within this describe section
    afterEach(() => {
        jest.restoreAllMocks();
        jest.resetAllMocks();
    });

    it('should be defined', () => {
        expect(partsController).toBeDefined();
        expect(partsService).toBeDefined();
    });

    describe('findAll', () => {
      it('should return an array of parts', async () => {
        const result: Part[] = [{ name: 'TestPart' }];

        jest.spyOn(partsService, 'findAll').mockImplementation(async (): Promise<Part[]> => Promise.resolve(result));

        const response = {
            json: (body?: any) => {},
            status: (code: number) => HttpStatus.OK,
        };

        expect(await partsController.getParts(response)).toBe(result);
      });
    }); 
});

我还没有亲自测试过代码,因此可以尝试一下(不太确定“部件控制器”中“响应”类型的响应模拟)。
关于零件控制器,尽管您应该利用来自express的Response类型的方式-尝试如下重写代码:

import { Controller, Get, Response, HttpStatus, Param, Body, Post, Request, Patch, Delete, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller('api/parts')
export class PartController {
  constructor(private readonly partsService: partsService) { }

  @Get()
  public async getParts(@Response() res: Response) { // <= see Response type from express being used here
    const parts = await this.partsService.findAll();
    return res.status(HttpStatus.OK).json(parts);
  }
}

最后看看Nest官方文档的这一部分,也许它可以为您提供一些有关您要实现的目标的见解:
-Nest testing section
-Nest library approach

在页面的几乎开头的第二个链接中,https://docs.nestjs.com/controllers#request-object部分中指出以下内容:

  
      
  • 为与跨基础HTTP平台(例如Express和Fastify)的键入兼容,Nest提供@Res()和@Response()   装饰。 @Res()只是@Response()的别名。两者都直接   公开底层的本机平台响应对象接口。什么时候   使用它们,您还应该导入基础的类型   库(例如@ types / express)以充分利用。请注意   您在方法处理程序中注入@Res()或@Response()   嵌套到该处理程序的特定于库的模式,您将成为   负责管理响应。这样做时,您必须发出   通过对响应对象进行调用来进行某种响应(例如,   res.json(...)或res.send(...)),否则HTTP服务器将挂起。
  •   

希望它会有所帮助,不要犹豫发表评论,或者在找到其他解决方案的情况下分享您的解决方案! :)

欢迎来到StackOverflow平台!