在 Angular 中对服务进行单元测试时,规范没有期望
Spec has no expectations when unit testing a Service in Angular
所以我的测试通过了,但是这是一个名为 should get the notes
的单元测试,用于 NoteService
,当 ng test
是 运行 时,它在 Karma 中的名称是喜欢
SPEC HAS NO EXPECTATIONS should get the notes
我尝试测试的方法如下:
@Injectable()
export class NoteService {
readonly baseUrl = "https://localhost:4200";
readonly httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
constructor(private httpClient: HttpClient) { }
getNotes(): Observable<Note[]> {
return this.httpClient.get<Note[]>(this.baseUrl + `/notes`, this.httpOptions);
}
单元测试是这样的:
describe('NoteService', () => {
let service: NoteService;
const mockList = [
{
"id": "id1",
"title": "First note",
"description": "This is the description for the first note",
"categoryId": "1"
},
{
"id": "id2",
"title": "Second note",
"description": "This is the description for the first note",
"categoryId": "2"
}]
beforeEach(() => {
TestBed.configureTestingModule({imports: [HttpClientTestingModule],
providers: [NoteService]});
service = TestBed.inject(NoteService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should get the notes', fakeAsync(() => {
service.getNotes().subscribe((val) => {
expect(val).toBe(mockList);
});
}));
});
所以,为什么说“SPEC HAS NO EXPECTATIONS”呢?我的单元测试有问题吗?我应该如何调整它才能使其正常工作?
这里不需要fakeAsync
。您应该使用 done()
来告诉测试它已经完成:
it('should get the notes',((done: DoneFN) => {
service.getNotes().subscribe((val) => {
expect(val).toBe(mockList);
done();
});
}));
所以我的测试通过了,但是这是一个名为 should get the notes
的单元测试,用于 NoteService
,当 ng test
是 运行 时,它在 Karma 中的名称是喜欢
SPEC HAS NO EXPECTATIONS should get the notes
我尝试测试的方法如下:
@Injectable()
export class NoteService {
readonly baseUrl = "https://localhost:4200";
readonly httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
constructor(private httpClient: HttpClient) { }
getNotes(): Observable<Note[]> {
return this.httpClient.get<Note[]>(this.baseUrl + `/notes`, this.httpOptions);
}
单元测试是这样的:
describe('NoteService', () => {
let service: NoteService;
const mockList = [
{
"id": "id1",
"title": "First note",
"description": "This is the description for the first note",
"categoryId": "1"
},
{
"id": "id2",
"title": "Second note",
"description": "This is the description for the first note",
"categoryId": "2"
}]
beforeEach(() => {
TestBed.configureTestingModule({imports: [HttpClientTestingModule],
providers: [NoteService]});
service = TestBed.inject(NoteService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should get the notes', fakeAsync(() => {
service.getNotes().subscribe((val) => {
expect(val).toBe(mockList);
});
}));
});
所以,为什么说“SPEC HAS NO EXPECTATIONS”呢?我的单元测试有问题吗?我应该如何调整它才能使其正常工作?
这里不需要fakeAsync
。您应该使用 done()
来告诉测试它已经完成:
it('should get the notes',((done: DoneFN) => {
service.getNotes().subscribe((val) => {
expect(val).toBe(mockList);
done();
});
}));