如何使用nestJS模拟Jest中的服务功能?

问题描述 投票:0回答:1

我需要一些帮助,在nestJS内部进行单元测试,我需要模拟getTokenRest函数以返回true,到目前为止,单元测试要求我模拟AuxService的其他不需要模拟的功能的问题,具体取决于我需要拉取几个函数并模拟它们的测试,你能帮我吗?我模拟 getTokenRest 做错了吗?

基本上我的服务中有 6 个直接从 auxService 使用的函数,但唯一需要模拟的是 getTokenRest ,其余的不需要它

看起来他希望我在模拟中使用所有 auxService 函数

TypeError: this.auxService.getConsumer is not a function

  12 |   ) {}
  13 |   async getUser(code: string): Promise<any> {
  14 |     const emviromment = this.auxService.getEmviromment(); 
> 15 |     const consumer = this.auxService.getConsumer();

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [Controller],
      providers: [
        Service,
        {
          provide: HttpService,
          useValue: {
            get: jest.fn(),
          },
        },
        {
          provide: AuxService,
          useValue: {
            getTokenRest: jest.fn(() => true),
            getEmviromment: jest.fn(() => 'test1'),
          },
        },
      ],
    }).compile();

    controller = module.get< Controller >(
      Controller,
    );
    service = module.get< Service >(
      Service,
    );
    httpService = module.get<HttpService>(HttpService);
    auxService = module.get<AuxService>(AuxService);
  });
 it('return status 200', async () => {
    const data = new Dto();
    data.code = '12345678901';

    const mockResponseObject = {
      status: jest.fn().mockReturnThis(),
      send: jest.fn(),
    };

    const mockResponse: AxiosResponse = {
      data: mock.sucess.data,
      status: mock.sucess.status,
      statusText: 'OK',
      headers: headers,
      config: { headers },
    };

    jest.spyOn(httpService, 'get').mockImplementation(() => of(mockResponse));
    const result = await controller.getUser(
      data,
      mockResponseObject,
    );
    expect(result.status).toEqual(mockResponse.status);
  });

服务

  async getUser(code: string): Promise<any> {
    const emviromment = this.auxService.getEmviromment();
    const consumer = this.auxService.getConsumer();
    const token = this.auxService.getToken();
    const option = this.getOption(code, emviromment, consumer, token);
    return this.DataRequest(option, emviromment);
  }

辅助服务

  public getEmviromment(): any {
    return emviromment;
  }

  public getConsumer(): any {
    return consumer;
  }

  public getToken() {
    return token;
  }

typescript jestjs nest
1个回答
0
投票

您需要更新以下代码

{
  provide: AuxService,
  useValue: {
    getTokenRest: jest.fn(() => true),
    getEmviromment: jest.fn(() => 'test1'),
  },
},

{
  provide: AuxService,
  useValue: {
    getTokenRest: jest.fn(() => true),
    getEmviromment: jest.fn(() => 'test1'),
    getConsumer: jest.fn(() => 'consumer'),
  },
},
© www.soinside.com 2019 - 2024. All rights reserved.