【问题标题】:How to unit test this prisma.service如何对这个 prisma.service 进行单元测试
【发布时间】:2022-11-12 14:05:25
【问题描述】:

我在单元测试时遇到问题棱镜服务.ts文件:

import { INestApplication, Injectable } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient {
  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit', async () => {
      await app.close();
    });
  }
}

prisma.service.spec.ts我目前看起来像这样:

import { INestApplication } from '@nestjs/common';
import { NestFastifyApplication } from '@nestjs/platform-fastify';
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from './prisma.service';

const MockApp = jest.fn<Partial<INestApplication>, []>(() => ({
  close: jest.fn(),
}));

describe('PrismaService', () => {
  let service: PrismaService;
  let app: NestFastifyApplication;

  beforeEach(async () => {
    app = MockApp() as NestFastifyApplication;
    const module: TestingModule = await Test.createTestingModule({
      providers: [PrismaService],
    }).compile();

    service = module.get<PrismaService>(PrismaService);
  });

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

  describe('enableShutdownHooks', () => {
    it('should call $on and successfully close the app', async () => {

      const spy = jest.spyOn(PrismaService.prototype, '$on')
      .mockImplementation(async () => {
        await app.close();
      });

      await service.enableShutdownHooks(app);

      expect(spy).toBeCalledTimes(1);
      expect(app.close).toBeCalledTimes(1);
      spy.mockRestore();
    });
  });
});

但是,这不会测试第 8 行棱镜服务.ts

await app.close();

因为我在嘲笑this.$on('beforeExit', 回调),以及其原始实现的副本。 即使我不嘲笑它,应用程序关闭()永远不会被调用。

有没有办法测试这条线?

【问题讨论】:

    标签: unit-testing jestjs nestjs


    【解决方案1】:

    你可以尝试使用回调:

    jest
      .spyOn(service, '$on')
      .mockImplementation(async (eventType, cb) => cb(() => Promise.resolve()))
    
    await service.enableShutdownHooks(app);
    
    expect(service.$on).toBeCalledTimes(1);
    
    

    这允许您使用回调来调用 await app.close() 所在的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-30
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多