加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

测试 – 如何仅在一次测试中覆盖Angular 5中的Provider?

发布时间:2020-12-17 07:16:36 所属栏目:安全 来源:网络整理
导读:在我的一个单元测试文件中,我必须使用不同的模拟多次模拟相同的服务. import { MyService } from '../services/myservice.service';import { MockMyService1 } from '../mocks/mockmyservice1';import { MockMyService2 } from '../mocks/mockmyservice2';de
在我的一个单元测试文件中,我必须使用不同的模拟多次模拟相同的服务.

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存在,但我没有设法在我的测试中使用它.当我在“它”中使用它时,提供者不会改变.我没有设法找到调用此函数的示例.你能解释一下如何正确使用它吗?或者你有另一种方法可以做到这一点?

解决方法

如果服务是作为公共财产注入的,例如:

@Component(...)
class MyComponent {
  constructor(public myService: MyService)
}

你可以这样做:

it('...',() => {
  component.myService = new MockMyService2(...); // Make sure to provide MockMyService2 dependencies in constructor,if it has any.
  fixture.detectChanges();

  // Your test here...
})

如果注入的服务存储在私有属性中,则可以将其编写为(component as any).myServiceMockMyService2 = new MockMyService2(…);绕过TS.

它不漂亮,但它的工作原理.

至于TestBed.overrideProvider,我对这种方法没有运气(如果它有效会更好):

it('...',() =>{
  TestBed.overrideProvider(MyService,{ useClass: MockMyService2 });
  TestBed.compileComponents();
  fixture = TestBed.createComponent(ConfirmationModalComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();

  // This was still using the original service,not sure what is wrong here.
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读