首页 > 解决方案 > NestJs 测试的性能问题

问题描述

我开始为我们的应用程序编写一些测试,因为它的性能似乎有些问题。

仅此测试就需要 10.842 秒!(根据笑话输出)

这似乎与注入模拟存储库有关,因为 Nest CLI 附带的标准测试运行顺利。但是由于我模拟了整个存储库,所以我不应该与数据库连接有任何延迟,所以我感到困惑。

import { ApplicationService } from '../application.service';
import { ApplicationRepository } from '../application.repository';
import { Test } from '@nestjs/testing';
import { ApplicationController } from '../application.controller';
import { ApplicationDTO } from '../DTO/applicationDTO';

describe('ApplicationService', () => {
  let service: ApplicationService;
  let mockRepo;
  beforeEach(async () => {
    mockRepo = {
      applications: [
      {id: 1, type: 'DATABASE', name: 'WhatsApp', access: 'ACCESS', user_access: 'HIGH', group: 'Nice', connection: 'aaaaaaaaaaaaaaa'},
      {id: 2, type: 'DATABASE', name: 'Telegram', access: 'ACCESS', user_access: 'LOW', group: 'Badguy', connection: 'aaaaaaaaaaaaaaa'},
    ],
    find() {
      return this.applications;
    },
    create(application) {
      this.applications.push(application);
      return { save() {
        return;
      }};
    },
    delete(id) {
      this.applications = this.applications.splice(0, id);
    },
  };
    const mockRepositoryProvider = {
      provide: ApplicationRepository,
      useValue: mockRepo,
    };
    const module = await Test.createTestingModule({
      controllers: [ApplicationController],
      providers: [ApplicationService, mockRepositoryProvider],
    }).compile();
    service = module.get<ApplicationService>(ApplicationService);
  });

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

  it('should return all applications', () => {
    expect(service.findAll()).toBe(mockRepo.applications);
  });

  it('should add a application', () => {
    const application = new ApplicationDTO(
      { id: 4, type: 'DATABASE', name: 'WhatsApp', access: 'ACCESS', user_access: 'ACCESS', group: 'Nice', connection: 'aaaaaaaaaaaaaaa'},
      );
    service.add(application);
    expect(service.findAll()).toContainEqual(
      expect.objectContaining(
        { id: 4, type: 'DATABASE', name: 'WhatsApp', access: 'ACCESS', user_access: 'ACCESS', group: 'Nice', connection: 'aaaaaaaaaaaaaaa'},
    ));
  });
});

标签: nestjs

解决方案


我想,没关系。Nest 应用程序启动大约需要 10 秒,如果您添加更多测试,时间不会显着增加。


推荐阅读