【发布时间】:2020-02-03 15:23:07
【问题描述】:
我有以下测试代码:
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {inject, TestBed} from '@angular/core/testing';
import {AviorBackendService} from './avior-backend.service';
describe('AviorBackendService', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [AviorBackendService],
}));
it('should be created', () => {
const service: AviorBackendService = TestBed.get(AviorBackendService);
expect(service).toBeTruthy();
});
// Inject the `done` method. This will tell the test suite that asynchronous methods are being called
// and it will mark the test as failed if within a specific timeout (usually 5s) the `done` is not called
it('expects service to fetch data with proper sorting', (done) => {
const service: AviorBackendService = TestBed.get(AviorBackendService);
// tslint:disable-next-line: prefer-const
let httpMock: HttpTestingController;
service.getUserCollection().subscribe(data => {
expect(data.length).toBe(7);
const req = httpMock.expectOne('http://localhost:3000/users');
expect(req.request.method).toEqual('GET'); // Then we set the fake data to be returned by the mock
req.flush({firstname: 'Chad'});
done(); // Mark the test as done
}, done.fail); // Mark the test as failed if something goes wrong
});
});
我需要为提供的函数编写一个原型测试(然后我将为其他类似函数编写其余部分)。我仍在学习如何编写测试,据我所知,我需要使用模拟,但我不明白如何。 我要测试的代码是:
getUserCollection() {
// withCredentials is very important as it passes the JWT cookie needed to authenticate
return this.client.get<User[]>(SERVICE_URL + 'users', { withCredentials: true });
}
我的测试代码报错Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
更新
我的 user-collection.model.ts:
import { User } from './user.model';
export interface UserCollection {
user: User[];
}
我的 user.model.ts:
import { Role } from './role';
// was class and not interface!
export interface User {
_id: number;
mandator?: number;
loginId: string;
lastname: string;
firstname: string;
password: string;
eMail: string;
group?: string;
role?: Role;
active?: boolean;
token?: string;
}
【问题讨论】:
标签: angular jasmine karma-jasmine