Expanding on Andrei Gatej's suggestion, we can modify the token to be a getter in order to restrict external classes/contexts from writing to it. This approach will make it easier to mock the token for unit testing purposes.
An implementation could look like this:
export class MyService {
private _token: string;
get token(): string {
return this._token;
}
// assign new token values using this._token = ....
public myMethod(): Promise<boolean> {
if(!this.token) // perform some action
else // perform another action
}
}
In your spec file, assuming it is already set up:
it('should execute the if block', async(done) => {
spyOnProperty(service, 'token', 'get').and.returnValue(null);
await service.myMethod();
await fixture.whenStable();
// add additional assertions here
});
it('should execute the else block', async(done) => {
spyOnProperty(service, 'token', 'get').and.returnValue('a sample token');
await service.myMethod();
await fixture.whenStable();
// add more assertions as needed
});