Angular 带茉莉花/业力的有角度的模拟场/财产
我试图测试一个组件,该组件使用一个在方法组件内调用属性的服务。我需要根据测试模拟和更改该属性 我有这个:Angular 带茉莉花/业力的有角度的模拟场/财产,angular,unit-testing,jasmine,karma-jasmine,karma-runner,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 } } }
export class XService{
xProperty:boolean;
}
export class XComponent{
ctor(private xService:XService){
}
xMethod():void{
if(xService.xProperty){
//some code
}
}
}
我尝试创建一个mock并在beforeach方法中添加属性
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);
});
it('x验证',()=>{
xServiceMock.xProperty=true;
fixture.detectChanges();
component.xMethod();这可以帮助您:
基本上,当您在configureTestingModule
中提供mock/spy/stub而不是真正的服务时,您需要在之后使用TestBed获得它。get()
在大多数情况下,使用TestBed测试角度服务会导致过载。请检查我的答案您可以为您的服务使用mock
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);
});
it('x验证',()=>{
fixture.detectChanges();
xMethod();