我正在尝试测试一个组件,该组件使用具有在方法组件内部调用的属性的服务。我需要根据测试模拟和更改该属性。
我有这个:
export class XService{
xProperty:boolean;
}
export class XComponent{
ctor(private xService:XService){
}
xMethod():void{
if(xService.xProperty){
//some code
}
}
}
我试过它创建一个模拟并在 beforeEach 方法中添加属性
beforeEach(() => {
/**more code**/
xServiceMock = jasmine.createSpyObj(['xMethodService']);
xServiceMock ['xProperty'] = false;
});
在我必须更改其中一项测试中的值之前,它一直有效。当我这样做时,该值不会刷新。
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);
});
你知道我是否可以用 Jasmine 模拟该属性吗?可能吗?
最佳答案
你可以为你的服务使用模拟
class MockXService extends XService{
xProperty = false; // set a fake value here
}
以这种方式将服务添加到提供者
beforeEach(async(() => {
TestBed.configureTestingModule({
...,
declarations: [XComponent],
providers: [
{ provide: XService, useClass: MockXService },
],
})
和你的测试
it('x validation', () => {
fixture.detectChanges();
component.xMethod();<<<-- When it calls the method the change to TRUE is not refreshed
expect(/****/).toBe(false);
});
关于带有 Jasmine/Karma 的 Angular Mock 字段/属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907595/