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

Jest TypeError: configService.get is not a function

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

I try to test a new class and the constructor, I have a 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',
        });
    }
}

And this is my test class:

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();
  });
});

When I try to run my test I have this error:

enter image description here

If someone have a idea of a solution, I would like to have an explanation.

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

Since you override your ConfigService provider by providing a factory, you should define a get-function on the returned object inside your factory function. Try something like:

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