patrick.oneill
patrick.oneill

Reputation: 51

Mock or override a module import in an angular-cli unit test

Hi I am using Angular 2 developed with the angular-cli.

I have a simple streaming service that is composed of an imported streaming module. I want to mock the imported module with another mock module but can't figure out how.

My service class is like so

import { streaming } from './streaming'

@Injectable()
export class StreamingService {


  constructor() {}

  streaming = streaming;
}

And my test is the standard generated test spec file

import { streaming } from './streaming'
import { mockStreaming } from './mock-streaming'

    describe('Service: Streaming', () => {
      beforeEach(() => {


        spyOn(streaming);
        TestBed.configureTestingModule({
          providers: [StreamingService],
          imports: mockStreaming
        })

     });

I am wondering should I include the streaming property as a param in the constructor function but I don't want to do it that way.

Is there something I can do in the karma.conf or test.ts file?

Upvotes: 1

Views: 3113

Answers (1)

Supamiu
Supamiu

Reputation: 8731

You can create a MockStreamingService which extends StreamingService:

@Injectable()
export class MockStreamingService {


  constructor() {}
  //And then mock methods, properties etc...
}

And then in your test:

describe('Service: Streaming', () => {
  beforeEach(() => {


    spyOn(streaming);
    TestBed.configureTestingModule({
      providers: [{provide:StreamingService, useClass:MockStreamingService}]
    })

 });

Upvotes: 1

Related Questions