我正在单元测试一个表示组件。我嘲笑它的一个服务有一个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);
});
});
在这种情况下,您总是可以创建一个mock类,而不是jasmine.createSpyObj
。我以前从未嘲笑过getters
,但我认为有时去模拟课比去jasmine.createSpyObj
要好。
试试这个:
class MockSessionService {
get user() {
return of(new User());
}
}
....
providers: [{ provide: SessionService, useClass: MockSessionService }]
尝试以最简单的方式定义您的存根
const sessionService = {
user:of(new User());
}