[英]Angular 2 unit tests: How to override a single provider in TestBed (for unit tests for a service, not a component, with service dependencies)?
I have:我有:
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
DocumentsLoaderSvc,
{ provide: MgrSvc, useClass: MockMgrSvc },
{ provide: URLLoaderSvc, useClass: MockURLLoaderSvcWhenData}
]
});
});
How do I override URLLoaderSvc with another mock, in an "it" case with its own unique requirement?在具有自己独特要求的“it”情况下,如何使用另一个模拟覆盖 URLLoaderSvc? Is there something like TestBed.overrideProvider... Right now, I have each it statement in its own "describe", with its own beforeEach.
有没有像 TestBed.overrideProvider 之类的东西……现在,我在自己的“描述”中拥有每个 it 语句,以及它自己的 beforeEach。
Maybe your best bet is to just make the mock configurable to suit the needs of different test cases.也许你最好的选择是让模拟可配置以适应不同测试用例的需求。 Keep it as an instance and use
useValue
instead of useClass
保持它作为一个实例并使用
useValue
而不是useClass
let urlLoderSvc: URLLoaderSvc;
beforeEach(() => {
urlLoaderSvc = new URLLoaderSvc();
TestBed.configureTestingModule({
providers: [
DocumentsLoaderSvc,
{ provide: MgrSvc, useClass: MockMgrSvc },
{ provide: URLLoaderSvc, useValue: urlLoaderSvc }
]
});
});
Now in your it
test cases, you can just configure the urlLoaderSvc
instance to do whatever you want.现在,在您的
it
测试的情况下,你可以配置urlLoaderSvc
实例做任何你想要的。
You can use ts-mockery
and Mock.extend
in every beforeEach
where you need it.您可以在每个
beforeEach
需要的地方使用ts-mockery
Mock.extend
和Mock.extend
。 The problem here is that the service at this point is already injected in the component - re-providing it will not update the already injected instance.这里的问题是此时的服务已经被注入到组件中——重新提供它不会更新已经注入的实例。 You would need to create your fixture for every test where you change the provided instances in this case.
在这种情况下,您需要为每次更改提供的实例的测试创建夹具。 It is easier to have a flexible mock instance instead which you can configure before every test.
使用灵活的模拟实例更容易,您可以在每次测试之前对其进行配置。
But sometimes it is needed, yes, for example if you have something like a repository service which needs an http service call and this call would need to be tested for success, fail and blocking to make sure that the repo service reacts correctly.但有时它是需要的,是的,例如,如果您有一个需要 http 服务调用的存储库服务,并且需要测试此调用是否成功、失败和阻塞以确保 repo 服务正确响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.