如何仅针对一项测试覆盖 Angular 5 中的 Provider? [英] How override Provider in Angular 5 for only one test?

查看:21
本文介绍了如何仅针对一项测试覆盖 Angular 5 中的 Provider?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个单元测试文件中,我必须用不同的模拟多次模拟相同的服务.

In one of my unit test files, I have to mock several times the same service with different mocks.

import { MyService } from '../services/myservice.service';
import { MockMyService1 } from '../mocks/mockmyservice1';
import { MockMyService2 } from '../mocks/mockmyservice2';
describe('MyComponent', () => {

    beforeEach(async(() => {
        TestBed.configureTestingModule({
        declarations: [
            MyComponent
        ],
        providers: [
            { provide: MyService, useClass: MockMyService1 }
        ]
        })
        .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(MapComponent);
        mapComponent = fixture.componentInstance;
        fixture.detectChanges();
    });

    describe('MyFirstTest', () => {
        it('should test with my first mock', () => {
            /**
             * Test with my first mock
             */
        });
    });

    describe('MySecondTest', () => {
        // Here I would like to change { provide: MyService, useClass: MockMyService1 } to { provide: MyService, useClass: MockMyService2 }

        it('should test with my second mock', () => {
            /**
             * Test with my second mock
             */
        });
    });
});

我看到函数 overrideProvider 存在,但我没有设法在我的测试中使用它.当我在它"中使用它时,提供者不会改变.我没有设法找到调用此函数的示例.你能解释一下如何正确使用它吗?或者您有其他方法可以做到这一点吗?

I see that the function overrideProvider exists, but I did not manage to use it in my test. When I use it in a "it", the provider doesn't change. I didn't manage to find an example where this function is called. Could you explain me how to use it properly? Or have you an other method to do that?

推荐答案

从 angular 6 开始,我注意到 overrideProvideruseValue 属性一起使用.因此,为了使其工作,请尝试以下操作:

As of angular 6 I noticed that overrideProvider works with the useValue property. So in order to make it work try something like:

class MockRequestService1 {
  ...
}

class MockRequestService2 {
  ...
}

然后像这样写测试床:

// example with injected service
TestBed.configureTestingModule({
  // Provide the service-under-test
  providers: [
    SomeService, {
      provide: SomeInjectedService, useValue: {}
    }
  ]
});

每当你想覆盖提供者时,只需使用:

And whenever you want to override the provider just use:

TestBed.overrideProvider(SomeInjectedService, {useValue: new MockRequestService1()});
// Inject both the service-to-test and its (spy) dependency
someService = TestBed.get(SomeService);
someInjectedService = TestBed.get(SomeInjectedService);

要么在 beforeEach() 函数中,要么放在 it() 函数中.

Either in a beforeEach() function or place it in an it() function.

这篇关于如何仅针对一项测试覆盖 Angular 5 中的 Provider?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆