简体   繁体   English

NestJS Jest 错误:TypeError:无法读取未定义的属性(读取“[来自所需配置的任何变量]”)

[英]NestJS Jest error: TypeError: Cannot read properties of undefined (reading '[any variable from required config]')

While trying to cover out project in unit tests using nest's jest I've bumped into a problem of a testing module not being able to pull variables from config.在尝试使用 nest 的笑话在单元测试中覆盖项目时,我遇到了一个测试模块无法从配置中提取变量的问题。

Basically, I have an EmailService, I want to test it, I use it as a Provider in my testing module.基本上,我有一个 EmailService,我想测试它,我在我的测试模块中将它用作提供者。 Naturally, as EmailService takes ConfigService in its constructor to pull some variables from config (that initially come from env) I put ConfigService into the providers array as well... well, then upon initialization testing module drops NestJS Jest error: TypeError: Cannot read properties of undefined (reading 'region')自然地,由于 EmailService 在其构造函数中使用 ConfigService 从配置中提取一些变量(最初来自 env),我也将 ConfigService 放入 providers 数组中......好吧,然后在初始化测试模块时丢弃 NestJS Jest 错误:TypeError:无法读取未定义的属性(阅读“区域”)

note: region variable is taken from env in a registered config module注意:区域变量取自已注册配置模块中的 env

code example of my test that throws我抛出的测试的代码示例

describe('EmailService', () => {
    let emailService: EmailService;
    let configService: ConfigService;

    beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
            providers: [EmailService, ConfigService],
        }).compile();

        emailService = module.get<EmailService>(EmailService);
        configService = module.get<ConfigService>(ConfigService);
    });

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

I have came to the conclusion that it throws an error specifically because EmailService takes ConfigService in it's constructor in this way:我得出的结论是它会抛出一个错误,因为 EmailService 以这种方式在其构造函数中采用了 ConfigService:

export class EmailService {
    private readonly config: IAwsConfig;
    private readonly region: IRegion;

    constructor(private readonly configService: ConfigService) {
        this.config = this.configService.get('aws');
        this.region = this.config.region;
    }

aditional info: both EmailService and ConfigService work just fine during a normal runtime, it only fails during jest testing附加信息:EmailService 和 ConfigService 在正常运行时都工作得很好,它只在玩笑测试时失败

seems like this.configService.get method returns 'undefined' during a test run and i'm, not sure why or how to fix it.似乎 this.configService.get 方法在测试运行期间返回“未定义”,我不确定为什么或如何修复它。 Any ideas?有任何想法吗?

Was not able to find an answer for 2 hours straight, but then, 10 minutes after asking a question, there you go, an answer.连续 2 个小时都找不到答案,但是在提出问题 10 分钟后,go 给了你一个答案。

Seems like ConfigService doesn't provide configs during jest testing so you have to provide it in the testing module with replaced get method, something like such:似乎 ConfigService 在玩笑测试期间不提供配置,因此您必须在测试模块中使用替换的 get 方法提供它,如下所示:

providers: [
        EmailService,
        {
          provide: ConfigService,
          useValue: {
            get: jest.fn((key: string) => {
              return hardcodedConfigFromWithinTheTestFile;
            }),
          },
        },
      ],

In case you don't want to import the entire ConfigService but just the config values themselves, then you use them in the test as follows:)如果您不想导入整个 ConfigService 而只是导入配置值本身,那么您可以在测试中使用它们,如下所示:)

// my-config.ts
import { registerAs } from '@nestjs/config';

export default registerAs('myConfig', () => ({ propA: 'aa', propB: 123 }));
import { Inject } from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import myConfig from './my-config.ts';

export class EmailService {
  private propA: string;
  private propB: number;

  constructor(
    @Inject(myConfig.KEY) config: ConfigType<typeof myConfig>
  ) {
    this.propA = config.propA;
    this.propB = config.propB;
  }
}
import { ConfigModule, registerAs } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';

describe('Test', () => {
  const configValues = { propA: 'aa', proprB: 123 };
  const config = registerAs('testConfig', () => configValues);

  beforeEach(async () => {
    const app: TestingModule = await Test.createTestingModule({
      imports: [ConfigModule.forFeature(config)],
      providers: [EmailService],
    }).compile();
  });

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 笑话错误:TypeError:无法读取未定义的属性(读取“发送”) - Jest error: TypeError: Cannot read properties of undefined (reading 'send') 笑话:- TypeError:无法读取未定义的属性(读取“params”)。 开玩笑时出错 - Jest:- TypeError: Cannot read properties of undefined (reading 'params'). Error coming in jest 笑话 28:createJestExpect - TypeError:无法读取未定义的属性(读取“扩展”) - Jest 28: createJestExpect - TypeError: Cannot read properties of undefined (reading 'extend') 开玩笑:TypeError:无法读取未定义的属性(读取“getFileName”) - Jest: TypeError: Cannot read properties of undefined (reading 'getFileName') Jest Vuejs 测试 - 类型错误:无法读取未定义的属性(读取“参数”) - Jest Vuejs Test - TypeError: Cannot read properties of undefined (reading 'params') TypeError:无法读取未定义(读取“长度”)JEST 测试的属性 - TypeError: Cannot read properties of undefined (reading 'length') JEST test Jest 抛出类型错误:无法读取未定义的属性(读取“isFake”) - Jest throws TypeError: Cannot read properties of undefined (reading 'isFake') TypeError:无法读取未定义的属性(读取“html”)- Jest - TypeError: Cannot read properties of undefined (reading 'html') - Jest 接下来是测试库和 Jest:错误 TypeError:无法读取未定义的属性(读取“firstName”) - Next with testing library and Jest : error TypeError: Cannot read properties of undefined (reading 'firstName') 获取 Jest 错误 TypeError:在组件中使用 useParams 时无法读取未定义的属性(读取“匹配”)? - Getting Jest error TypeError: Cannot read properties of undefined (reading 'match') when using useParams in the component?
 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM