【问题标题】:Jest TypeError: configService.get is not a functionJest TypeError:configService.get 不是函数
【发布时间】:2021-03-11 17:18:12
【问题描述】:

我尝试测试一个新类和构造函数,我有一个 configService.get。

@Injectable()
export class StripeService {
    private stripe: Stripe;

    constructor(private configService: ConfigService) {
        const secretKey = configService.get<string>('STRIPE_SECRET') || '';
        this.stripe = new Stripe(secretKey, {
            apiVersion: '2020-08-27',
        });
    }
}

这是我的测试课:

import { Test, TestingModule } from '@nestjs/testing';
import { StripeService } from './stripe.service';
import { ConfigService } from '@nestjs/config';

const mockStripe = () => ({})

describe('StripeService', () => {
  let service: StripeService;

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

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

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

当我尝试运行我的测试时,我遇到了这个错误:

如果有人有解决方案的想法,我想解释一下。

【问题讨论】:

    标签: typescript testing jestjs nestjs


    【解决方案1】:

    由于您通过提供工厂来覆盖 ConfigService 提供程序,因此您应该在工厂函数内的返回对象上定义 get 函数。尝试类似:

    const mockStripe = () => ({get:() => undefined})
    

    【讨论】:

    • 成功了!谢谢。我会在 11 分钟内接受你的回复,因为之前我做不到
    猜你喜欢
    • 2019-03-28
    • 2022-06-10
    • 2019-09-26
    • 2017-06-25
    • 2019-10-16
    • 2021-03-24
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多