【问题标题】:Nestjs "Reference Error: File is not defined" only in testNestjs“参考错误:文件未定义”仅在测试中
【发布时间】:2021-09-22 01:39:10
【问题描述】:

我的测试套件无法运行,因为“文件”输入类型未定义。这仅在尝试运行测试时发生。该应用程序在开发中完美运行。下面是我的控制台输出。

$ nx run build-support-cases-api-core:test

> nx run build-support-cases-api-core:test 
 FAIL   build-support-cases-api-core  libs/build-support-cases/api/core/src/lib/__test__/buildSupportCase.service.spec.ts
  ● Test suite failed to run

    ReferenceError: File is not defined

      4 | export class CreateReceiptInput {
      5 |   @Field(() => String)
    > 6 |   public receipt: File;
        |                   ^
      7 |
      8 |   @Field(() => String)
      9 |   public vendorName: string;

      at Object.<anonymous> (../../../core/database/receipt/src/lib/dto/createReceipt.input.ts:6:19)
      at Object.<anonymous> (../../../core/database/receipt/src/lib/dto/createReceipt.dto.ts:1:1)

这里是完整的源文件

import { Field, ID, InputType } from "@nestjs/graphql";

@InputType()
export class CreateReceiptInput {
  @Field(() => String)
  public receipt: File;

  @Field(() => String)
  public vendorName: string;

  @Field(() => Date)
  public purchaseDate: Date;

  @Field(() => Number)
  public totalDollarAmount: number;

  @Field(() => String)
  public purchasedBy: string;

  @Field(() => String)
  public note: string;

  @Field(() => ID)
  public updateId?: number;
}

配置文件中是否有我遗漏的内容?如何解决这个问题,以便我的测试能够运行?

【问题讨论】:

  • File 通常来自哪里?它代表什么?
  • 从描述上看,它是一个提供文件信息并允许网页中的 JavaScript 访问其内容的接口。它来自打字稿。 microsoft.github.io/PowerBI-JavaScript/interfaces/…
  • 好吧,它代表什么?看起来该类型来自 lib 类型,ts-jest 可能在类型检查期间被丢弃。您可能应该有一个不是来自lib(前端类型)的专用类型
  • 表示CreateReceiptInput收据方法的输入类型。我将一个 CreateReceiptInput 类型的对象发布到我的 ReceiptService,在那里我将文件上传到 aws 并将它上传到的 url 保存到我的数据库中。没错,File 是前端类型,因为它来自 FormData。我应该以不同的方式处理这个问题吗?
  • 您没有导入File。它是一个接口,在其他地方定义。所以你必须导入它。

标签: typescript jestjs nestjs nrwl-nx


【解决方案1】:

问题是 File 存在于 typescript 中,但不存在于 NodeJS(或扩展名为 NestJS)中。但是,Blob 类型确实存在于 NestJS 中,因此如果您将其复制到新文件并导入,则 typescript 定义的文件类型可以正常工作。

export interface File extends Blob {
  readonly lastModified: number;
  readonly name: string;
}

import { Field, ID, InputType } from "@nestjs/graphql";
import { File } from "./interfaces";
@InputType()
export class CreateReceiptInput {
  @Field(() => String)
  public receipt: File;

  @Field(() => String)
  public vendorName: string;

  @Field(() => Date)
  public purchaseDate: Date;

  @Field(() => Number)
  public totalDollarAmount: number;

  @Field(() => String)
  public purchasedBy: string;

  @Field(() => String)
  public note: string;

  @Field(() => ID)
  public updateId?: number;
}

【讨论】:

    猜你喜欢
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多