制造业行业类别与代码:角模拟场 /属性与茉莉/业力(jasmine field)

我正在尝试测试一个组件,该组件使用一个方法组件内部调用的属性的服务。我需要根据测试来模拟和更改该属性。

我有这个:

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);
  });

你知道我是否可以用茉莉嘲笑那处房产吗?有可能吗?

2

您可以使用模拟为您的服务

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);
});
0

这可以帮助您:https://next.angular.io/guide/testing#always-get-the-service-from-an-injector

基本上,当您在configureTestingModule中提供模拟 / 间谍 / 存根而不是真正的服务时,您需要在TestBed.get()之后获得它。

-1

使用 TestBed 测试 Angular 服务在大多数情况下会导致过载。检查我的答案here

本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处

(232)
月份前面用on还是in:用“0”填充月份(asp month)
上一篇
Jquery判断是否存在某个class:jQuery:检查是否存在具有特定类名的div
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(60条)