'Angular unit test - property in mock service is undefined
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);
});
});
Solution 1:[1]
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 }]
Solution 2:[2]
Try to define your stub simplest way possible
const sessionService = {
user:of(new User());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AliF50 |
| Solution 2 | Antoniossss |
