![](/img/trans.png)
[英]Unable to mock a service and return data in angular unit test - says undefined
[英]Angular unit test - property in mock service is undefined
我正在對演示組件進行單元測試。 它的一項服務 I am mocking 有一個 getter 屬性 user。 該組件派生自另一個。 在其父級的 ngOnInit 上,訪問了 sessionService 的用戶屬性,但由於發現它未定義而失敗。 在這里嘗試的另一種方法是什么?
describe('MyComponent', () => {
let component: MyComponent, fixture: ComponentFixture<MyComponent>, el: DebugElement;
beforeEach(
waitForAsync(() => {
const sessionService = jasmine.createSpyObj('SessionService', ['']);
Object.defineProperty(sessionService, 'user', {
value: of(
new User()
)
});
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [...],
providers: [
{ provide: SessionService, useValue: sessionService }
]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
});
})
);
it('should have prev/next buttons', () => {
fixture.detectChanges();
console.log(el.nativeElement.outerHTML);
});
});
在這種情況下,您始終可以創建模擬 class 而不是jasmine.createSpyObj
。 我以前從來沒有嘲笑過getters
,但我認為有時候 go 比jasmine.createSpyObj
。
嘗試這個:
class MockSessionService {
get user() {
return of(new User());
}
}
....
providers: [{ provide: SessionService, useClass: MockSessionService }]
嘗試以最簡單的方式定義存根
const sessionService = {
user:of(new User());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.