简体   繁体   English

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

[英]Spec has no expectations when unit testing a Service in Angular

So my tests are passing but it's this one unit test named should get the notes for the NoteService which, when ng test is ran, its name in Karma is written like所以我的测试通过了,但是这个名为的单元测试should get the notes NoteService的注释,当运行ng test时,它在 Karma 中的名称写成

SPEC HAS NO EXPECTATIONS should get the notes SPEC没有期望应该得到笔记

The method that I am trying to test is the following:我要测试的方法如下:

@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);
  }

And the unit test is this:单元测试是这样的:

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);
    });
  }));
});

Therefore, why is it saying that "SPEC HAS NO EXPECTATIONS"?因此,为什么说“SPEC 没有期望”? Is it something wrong with my unit test?我的单元测试有问题吗? And how should I tweak it in order to make it work well?我应该如何调整它以使其正常工作?

You don't need the fakeAsync here.你不需要fakeAsync这里。 You should be using done() to tell the test it's been finished:您应该使用done()告诉测试它已经完成:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM