标签: nestjs-testing

使用 @Injectable Scope / @Inject(REQUEST) NestJS 测试类

我已经设置了 MongooseConfigService 来允许我们动态切换某些请求的连接字符串,并尝试正确设置测试。

@Injectable({scope: Scope.REQUEST})
export class MongooseConfigService implements MongooseOptionsFactory {
  constructor(
    @Inject(REQUEST) private readonly request: Request) {
  }
Run Code Online (Sandbox Code Playgroud)

然而,我在提供request测试上下文时遇到了困难。

  let service: Promise<MongooseConfigService>;
  
  beforeEach(async () => {
    const req = new JestRequest();
    
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        MongooseConfigService,
        {
          provide: getModelToken(REQUEST),
          inject: [REQUEST],
          useFactory: () => ({
            request: req,
          }),
        },
      ],
    }).compile();
    
    service = module.resolve<MongooseConfigService>(MongooseConfigService);
  });
Run Code Online (Sandbox Code Playgroud)

据我所知,已经在没有inject和 with/without 的情况下尝试过useValue,但是this.request在尝试运行测试时仍然未定义。

TIA

nestjs nestjs-testing

10
推荐指数
1
解决办法
4689
查看次数

开玩笑,抛出有关 node_modules 依赖项内导入的引用错误

我有一个 Nestjs monorepo 应用程序,可以通过 Jest 进行工作测试。这与全局单元测试有关,该测试从 package.json 中的 Nestjs CLI 创建的配置中获取配置。

我的 storage.service.ts 使用jimp其方法之一来调整图像大小。

这具有@jimp/types依赖关系 取决于@jimp/gif取决于gifwrap

对于在我的控制台中运行的每个测试,我都会看到以下错误:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at node_modules/.pnpm/gifwrap@0.9.2/node_modules/gifwrap/src/gifcodec.js:7:15
Run Code Online (Sandbox Code Playgroud)

我还使用 beforeAll() 和 afterAll() 钩子来关闭 Nestjs 模块。

笑话配置:

  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": ".",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "./coverage",
    "testEnvironment": "node",
    "roots": [
      "<rootDir>/apps/",
      "<rootDir>/libs/" …
Run Code Online (Sandbox Code Playgroud)

jestjs nestjs nestjs-testing

9
推荐指数
1
解决办法
2443
查看次数

Nestjs overrideProvider 与单元测试中的提供程序

我在 NestJS 中看到两种模拟服务进行单元测试的方法,第一种与我们在实际模块中定义提供程序相同,例如:

const module = await Test.createTestingModule({
  providers: [
    UserService,
    {
      provide: getRepositoryToken(User),
      useValue: mockUsersRepository,
    }
  ],
}).compile();
Run Code Online (Sandbox Code Playgroud)

以及方法的另一种方式overrideProvider。如下:

const module = await Test.createTestingModule({
  imports: [UserModule]
})
.overrideProvider(getRepositoryToken(User))
.useValue(mockUsersRepository)
.compile();
Run Code Online (Sandbox Code Playgroud)

有什么不同?

unit-testing nestjs nestjs-testing

9
推荐指数
2
解决办法
6060
查看次数

尽管在 package.json 中进行了配置,但在 monorepo 中对应用程序进行 Nestjs e2e 测试时,无法使用 jest 解决从库中导入 @app 的问题

我正在尝试对 monorepo 应用程序运行 e2e 测试,该应用程序还利用 monorepo 中的多个库,整个应用程序中的所有导入都使用“@app”导入来解析,例如import { ConfigService } from "@app/config"

但是,当尝试通过命令运行 e2e 测试时:

"test:public": "jest --config ./apps/public-microservice/test/jest-e2e.json",
Run Code Online (Sandbox Code Playgroud)

开玩笑抛出:

 Cannot find module '@app/config' from '../src/public-microservice.module.ts'
Run Code Online (Sandbox Code Playgroud)

我查看了@jmcdo29 的演示存储库,但找不到任何与我的配置不同的内容。

我注意到2019 年这里存在通过 jest 生成错误配置的问题,但它早已解决,并且我在 package.json 中的 jest 配置确实提到了:

    "moduleNameMapper": {
      "@app/config/(.*)": "<rootDir>/libs/config/src/$1",
      "@app/config": "<rootDir>/libs/config/src",
Run Code Online (Sandbox Code Playgroud)

而 package.json 脚本命令的本地目标文件仅包含:

{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": ".",
  "testEnvironment": "node",
  "testRegex": ".e2e-spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  }
}

Run Code Online (Sandbox Code Playgroud)

我的命令或配置中是否缺少某些内容?

我需要指定什么来告诉 jest 扩展 package.json 中可用的 jest 配置吗?

感谢您对此进行投资的任何帮助,谢谢。

jestjs nestjs nestjs-testing

6
推荐指数
1
解决办法
2327
查看次数

NestJS如何从graphql模块获取apolloClient以使用“apollo-server-testing”进行测试?

虽然标题类似于Access to Apollo server for NestJS GraphQL test,但问题本身很旧,并且该问题中的答案都解决了 Nestjs 中似乎不再存在的行为。

我遵循了这里的 PR https://github.com/nestjs/graphql/pull/1104以及其他几个线程,试图从测试模块获取 apolloClient 来对其运行测试查询,但没有成功。

Typescript 编译器支持的普遍错误是它根本不存在于 GraphQlModule 上。它在哪里?为什么它被删除了?我如何访问这个关键功能?

TypeError: Cannot read properties of undefined (reading 'executeOperation')

      71 | export function createTestClient(testingModule: TestingModule): apolloServerTesting.ApolloServerTestClient {
      72 |     const apolloServer = getApolloServer(testingModule);
    > 73 |     return apolloServerTesting.createTestClient(apolloServer as any);
         |                                ^
      74 | }
Run Code Online (Sandbox Code Playgroud)

基于PR创建的功能:

export function getApolloServer(app: INestApplicationContext): ApolloServerBase {
    try {
        const graphqlModule = app.get(GraphQLModule);
        return (graphqlModule as any).apolloServer;
    } catch (error) {}
    throw new Error( …
Run Code Online (Sandbox Code Playgroud)

graphql apollo-server nestjs nestjs-testing apollo-testing

5
推荐指数
0
解决办法
1137
查看次数

在 NestJS 中使用 Mongoose 测试服务

我正在尝试在 NestJS 中测试我的 LoggingService,虽然我看不到测试有任何问题,但我得到的错误是Error: Cannot spy the save property because it is not a function; undefined given instead

正在测试的函数(为简洁起见进行了修剪):

@Injectable()
export class LoggingService {
  constructor(
    @InjectModel(LOGGING_AUTH_MODEL) private readonly loggingAuthModel: Model<IOpenApiAuthLogDocument>,
    @InjectModel(LOGGING_EVENT_MODEL) private readonly loggingEventModel: Model<IOpenApiEventLogDocument>,
  ) {
  }
  
  async authLogging(req: Request, requestId: unknown, apiKey: string, statusCode: number, internalMsg: string) {
    
    const authLog: IOpenApiAuthLog = {
///
    }
    
    await new this.loggingAuthModel(authLog).save();
  }
}

Run Code Online (Sandbox Code Playgroud)

这几乎是我的第一次 NestJS 测试,据我所知,这是测试它的正确方法,考虑到错误在最后是正确的,它似乎是正确的。

describe('LoggingService', () => {
  let service: LoggingService;
  let mockLoggingAuthModel: IOpenApiAuthLogDocument;
  let request;
  
  beforeEach(async () …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing nestjs nestjs-testing

3
推荐指数
1
解决办法
5385
查看次数