I have a service in Angular:
export class AuthService {
apiURL = `${environment.apiURL}/${EndPoints.auth}`;
constructor(private http: HttpClient, private store: Store<AppState>) {}
loggedUser$ = this.store.select(selectIsUserLogged);
login(body: LoginData): Observable<ResponseUser> {
return this.http.post<ResponseUser>(
`${this.apiURL}/${EndPoints.login}`,
body,
{
withCredentials: true,
}
);
}
logout(): Observable<MessageResponse> {
return this.http.get<MessageResponse>(
`${this.apiURL}/${EndPoints.logout}`,
{
withCredentials: true,
}
);
}
register(body: RegisterData): Observable<MessageResponse> {
return this.http.post<MessageResponse>(
`${this.apiURL}/${EndPoints.register}`,
body
);
}
autoLogin(): Observable<ResponseUser> {
return this.http.get<ResponseUser>(
`${this.apiURL}/${EndPoints.autoLogin}`,
{
withCredentials: true,
}
);
}
}
And I want to write unit test to this service. This is my code:
describe('AuthService', () => {
let service: AuthService;
let testingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, StoreModule.forRoot({})],
providers: [AuthService],
});
service = TestBed.inject(AuthService);
testingController = TestBed.inject(HttpTestingController);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should user be register', (done) => {
const body: RegisterData = {
email: '[email protected]',
firstName: 'test',
lastName: 'test',
password: '12345678',
};
const messageResponse = {
message: 'User registered successfully',
};
service.register(body).subscribe((response) => {
expect(response).toBeTruthy();
});
const mokcReq = testingController.expectOne(
`${environment.apiURL}/${EndPoints.auth}/${EndPoints.register}`
);
mokcReq.flush(messageResponse.message);
testingController.verify();
});
});
And I have an error:
Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)
I try to extend default timeout, but problem is somewhere else.
Also i want to ask how to tests the others method from service. And I don’t know if understand correctly, when I tests register user will be create at the database and when I run tests next time I get the error that I want to create user with the same data.
Michał is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.