Warm tip: This article is reproduced from serverfault.com, please click

typescript-开玩笑TypeError:configService.get不是一个函数

(typescript - Jest TypeError: configService.get is not a function)

发布于 2020-11-29 16:36:05

我尝试测试一个新类和构造函数,我有一个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();
  });
});

当我尝试运行测试时,出现以下错误:

在此处输入图片说明

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

Questioner
Verdouze
Viewed
0
eol 2020-11-30 00:41:46

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

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