简体   繁体   English

在 angular-cli 单元测试中模拟或覆盖模块导入

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

Hi I am using Angular 2 developed with the angular-cli.嗨,我正在使用通过 angular-cli 开发的 Angular 2。

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?我可以在 karma.conf 或 test.ts 文件中做些什么吗?

You can create a MockStreamingService which extends StreamingService :您可以创建一个MockStreamingService扩展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}]
    })

 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM