在 Angular 中对服务进行单元测试时,规范没有任何期望

Que*_*eme 4 service unit-testing karma-jasmine angular

所以我的测试通过了,但这是一个以该命名的单元测试should get the notesNoteServiceng test运行时,它在 Karma 中的名称写为

规范没有期望应该得到注释

我试图测试的方法如下:

@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);
  }
Run Code Online (Sandbox Code Playgroud)

单元测试是这样的:

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);
    });
  }));
});
Run Code Online (Sandbox Code Playgroud)

那么,为什么说“SPEC没有期望”呢?我的单元测试有问题吗?我应该如何调整它才能使其正常工作?

Don*_*uwe 8

你不需要fakeAsync这里。您应该用来done()告诉测试它已经完成:

it('should get the notes',((done: DoneFN) => {
    service.getNotes().subscribe((val) => {
        expect(val).toBe(mockList);
        done();
    });
}));
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!问题是,我之前使用的是“done()”,但给了我这个错误:“错误:超时 - 异步函数未在 5000 毫秒内完成(由 jasmine.DEFAULT_TIMEOUT_INTERVAL 设置)”。因此,在挖掘了一些答案后,我将其更改为“fakeAsync”。因此,如何修复“done()”给我的超时错误? (2认同)