带有 Jasmine/Karma 的 Angular Mock 字段/属性

标签 angular unit-testing jasmine karma-jasmine karma-runner

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

我有这个:

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/

相关文章:

angular - 如何使用 Protractor typescript 使用 _ngcontent 和 span buttontext 单击元素

javascript - 在 Jquery 中工作时如何使用 Jasmine 测试文本颜色?

angular - 是否可以模拟 typescript 装饰器?

javascript || Angular2/6 : Calling setInterval multiple times but last timerId is not stopping even though clearInterval called

c# - 如何在 C#/VS 中构建自定义断言?

python - 在 Python 中测试抽象类

javascript - 使用 Angular 2 序列化和反序列化 JSON

javascript - 有没有办法防止使用浏览器后退按钮离开网页?

用于单元测试的 C# 通用存储库

angularjs - 对具有依赖项的 AngularJS 工厂进行单元测试