lehh / nestjs-soap

Nestjs module wrapper for soap npm package
MIT License
21 stars 15 forks source link

how to use in a unit test? #2

Closed bitsofinfo closed 3 years ago

bitsofinfo commented 3 years ago

How can I use this in a unit test?

lehh commented 3 years ago

You can do it like this:

// example.service.ts

import { Inject, Injectable } from '@nestjs/common';
import { Client } from 'nestjs-soap';

@Injectable()
export class ExampleService {
  constructor(@Inject('CLIENT_NAME') private readonly client: Client) {}

  example(): void {
    this.client.myFunctionAsync();
  }
}
// example.service.spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { Client } from 'nestjs-soap';
import { ExampleService } from './example.service';

const clientMock = () => ({
  myFunctionAsync: jest.fn(),
});

describe('ExampleService', () => {
  let service: ExampleService;
  let soap: Client;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ExampleService,
        {
          provide: 'CLIENT_NAME', // Here you need to use the same client name injected on the service
          useFactory: clientMock,
        },
      ],
    }).compile();

    service = module.get<ExampleService>(ExampleService);
    soap = module.get<Client>('CLIENT_NAME');
  });

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

  it('should call myFunctionAsync', () => {
    service.example();

    expect(soap.myFunctionAsync).toBeCalled();
  });
});
bitsofinfo commented 3 years ago

thanks!