I have an angular service that performs API calls. it has a method to login and store the access token in the service for the subsequent API call to use. When I run unit test, I first test the login method, then test the other API calls methods. But the other API calls test fail because the stored token become undefined. How do I preserve the service state so that I don’t need to login again in every spec?
api.service.ts
@Injectable({
providedIn: 'root'
})
export class ApiService {
private token?: string;
async login(username:string, password: string): Promise<boolean>{
const token = /* method to get token */;
this.token = token;
return true;
}
async someApiCall(): Promise<string>{
const res = /* fetch using this.token */
return res;
}
}
api.service.spec.ts
describe("ApiService", () => {
let service: ApiService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
TranslateModule.forRoot(),
],
});
service = TestBed.inject(ApiService);
});
it("should be created", () => {
expect(service).toBeTruthy();
});
it("can login", async () => {
const isLoggedIn = await service.login(
testenv.username,
testenv.password
);
expect(isLoggedIn).toBeTruthy();
});
it("can do some api call", async () => {
const res = await service.someApiCall();
expect(res).toBeTruthy();
});
});