I am aware of similar questions already asked, but absolutely nothing has solved my issue thus far. Perhaps I am missing something.
I have this service that has a getter I want to mock
export class UserService {
private activeUserSubject: BehaviorSubject<UserModel>;
constructor() {
this.activeUserSubject = new BehaviorSubject<UserModel>(UserHelper.getCurrentUser());
}
public get activeUserValue(): UserModel {
return this.activeUserSubject.value;
}
}
All the other answers suggest using SpyOnProperty but it just doesnt work for me. In my spec I attempt to create and mock it but I get the error Property activeUserValue does not have access type get.
describe('MyComponent', () => {
///other
let authenticationService: jasmine.SpyObj<UserService>;
beforeEach(async () => {
userService = jasmine.createSpyObj<UserService>(['activeUserValue']);
await TestBed.configureTestingModule({
imports: [
///
],
declarations: [
///
],
providers: [
{ provide: UserService, useValue: userService }
]
})
.compileComponents();
});
fit('should create', () => {
const spy = spyOnProperty(userService, 'activeUserValue', 'get').and.returnValue(of(getMockUser()));
fixture.detectChanges();
expect(spy).toBe(getMockUser());
});
}
What am I doing wrong?
CodePudding user response:
Keep in mind that when you do spyOnProperty(userService,
, you're saying that this getter
exists on the spyObject
you created which it doesn't. Once you have mocked UserService
, its implementation (of whether it uses a getter or what not) is out of the window and we should use the mock.
I would do the following (follow the comments with !!):
describe('MyComponent', () => {
///other
let authenticationService: jasmine.SpyObj<UserService>;
beforeEach(async () => {
userService = jasmine.createSpyObj<UserService>(['activeUserValue']);
// !! attach activeUserValue to the spyObject
userService.activeUserValue = of(getMockUser());
await TestBed.configureTestingModule({
imports: [
///
],
declarations: [
///
],
providers: [
{ provide: UserService, useValue: userService }
]
})
.compileComponents();
});
fit('should create', () => {
// !! remove this line
fixture.detectChanges();
expect(spy).toBe(getMockUser());
});
}