[英]Angular Mock field/property with Jasmine / Karma
I'm trying to test a component which uses a Service with a property called inside a method's component. 我正在尝试测试使用服务的组件,该组件具有在方法的组件内部调用的属性。 I need to mock and change that property depending on the test.
我需要根据测试来模拟和更改该属性。
I have this: 我有这个:
export class XService{
xProperty:boolean;
}
export class XComponent{
ctor(private xService:XService){
}
xMethod():void{
if(xService.xProperty){
//some code
}
}
}
I tried it creating a mock and adding the property in beforeEach method 我尝试过创建一个模拟并在beforeEach方法中添加属性
beforeEach(() => {
/**more code**/
xServiceMock = jasmine.createSpyObj(['xMethodService']);
xServiceMock ['xProperty'] = false;
});
That works well until I have to change the value in one of the tests. 在我必须更改其中一项测试的值之前,该方法效果很好。 When I do it, the value is not refreshed.
当我这样做时,该值不会刷新。
it('x validation', () => {
xServiceMock.xProperty = true;
fixture.detectChanges();
component.xMethod();<<<-- When it calls the method the change to TRUE is not refreshed
expect(/****/).toBe(false);
});
Do you know if I can mock that property with Jasmine? 你知道我可以用茉莉花嘲笑那个财产吗? Is it possible?
可能吗?
This can help you: https://next.angular.io/guide/testing#always-get-the-service-from-an-injector 这可以为您提供帮助: https : //next.angular.io/guide/testing#always-get-the-service-from-an-injector
Basically when you provide mock/spy/stub instead of real service in configureTestingModule
you need to get it afterwards with TestBed.get()
. 基本上,当您在
configureTestingModule
提供模拟/间谍/存根而不是实际服务时,需要在以后使用TestBed.get()
获得它。
you can use a mock for your service 您可以使用模拟服务
class MockXService extends XService{
xProperty = false; // set a fake value here
}
add the service to providers this way 通过这种方式将服务添加到提供商
beforeEach(async(() => {
TestBed.configureTestingModule({
...,
declarations: [XComponent],
providers: [
{ provide: XService, useClass: MockXService },
],
})
and your test 和你的测试
it('x validation', () => {
fixture.detectChanges();
component.xMethod();<<<-- When it calls the method the change to TRUE is not refreshed
expect(/****/).toBe(false);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.