I am unit testing a presentational component. One of its services I am mocking has a getter property, user. This component derives from another. On the ngOnInit of its parent the sessionService's user property is accessed and it fails as it finds it undefined. What's another approach to try here?
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);
});
});
CodePudding user response:
You can always create a mock class in this case instead of a jasmine.createSpyObj
. I have never mocked getters
before but I think sometimes it is better to go to mock class than jasmine.createSpyObj
.
Try this:
class MockSessionService {
get user() {
return of(new User());
}
}
....
providers: [{ provide: SessionService, useClass: MockSessionService }]
CodePudding user response:
Try to define your stub simplest way possible
const sessionService = {
user:of(new User());
}