angular - 即使成功,如何避免 "ERROR: Spec method has no expectations"?

标签 angular typescript unit-testing jasmine karma-jasmine

我有 Angular HTTP 服务,可以进行一些 HTTP 调用。 这是我的服务示例:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class APIService {
    constructor(private readonly http: HttpClient) {}

    public async getUsers<T>(): Promise<T[]> {
        return await this.http.get<T[]>('/api/users').toPromise();
    }
}

这是我的 APIService spec.ts 文件:

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { APIService } from './api.service';

describe('API Service', () => {
    let service: APIService;
    let controller: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [APIService]
        });

        service = TetsBed.get(APIService);
        controller = TestBed.get(HttpTestingController);
    });

    it('should create the API service', () => {
        expect(service).toBeTruthy();
    });

    it('should get users', () => {
        const expected = [{id: 1, email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="583d3539313469183c3735393136762c343c" rel="noreferrer noopener nofollow">[email protected]</a>'},
                          {id: 2, email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbbeb6bab2b7e99bbfb4b6bab2b5f5afb7bf" rel="noreferrer noopener nofollow">[email protected]</a>'}];

        service.getUsers<MyUserClass>().then((res) => {
            expect(res).toEqual(expected);
            controller.verify();
        });

        controller.expectOne('/api/users').flush(expected);
    });

});

一切似乎都正常,因为当我运行 ng test 时,我收到如下消息:

ERROR: 'Spec 'API Service should get users' has no expectations.'
HeadlessChrome 77.0.3865 (Windows 10.0.0): Executed 13 of 15 SUCCESS (0 secs / 0.256 secs)
HeadlessChrome 77.0.3865 (Windows 10.0.0): Executed 15 of 15 SUCCESS (0.42 secs / 0.28 secs)
TOTAL: 15 SUCCESS
TOTAL: 15 SUCCESS
TOTAL: 15 SUCCESS

当我在下一个代码下更改某些内容时,出现错误。

.then((res) => {
    // expect(res).toEqual(expected);
    expect(res).toBeNull();
    controller.verify();
});

所以上面的代码很好并且可以工作。

那么,为什么我收到一条错误消息:ERROR: 'Spec 'API Service should get users' has no Expects.'?有什么想法吗?

我猜,async/await可能会导致这个问题,因为我实际上并没有等待它,但是,它执行时没有错误,当我输入错误的数据时,它会失败。

我还尝试将所有内容包装到 async/fakeAsync 方法中 - 没有运气。

最佳答案

好吧,实际上(完成)解决了我的问题;

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { APIService } from './api.service';

describe('API Service', () => {
    let service: APIService;
    let controller: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [APIService]
        });

        service = TetsBed.get(APIService);
        controller = TestBed.get(HttpTestingController);
    });

    it('should create the API service', () => {
        expect(service).toBeTruthy();
    });

    it('should get users', (done) => {
        const expected = [{id: 1, email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f59098949c99c4b5919a98949c9bdb819991" rel="noreferrer noopener nofollow">[email protected]</a>'},
                          {id: 2, email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="492c242820257b092d2624282027673d252d" rel="noreferrer noopener nofollow">[email protected]</a>'}];

        service.getUsers<MyUserClass>().then((res) => {
            expect(res).toEqual(expected);
            controller.verify();
            done();
        });

        controller.expectOne('/api/users').flush(expected);
    });

});

关于angular - 即使成功,如何避免 "ERROR: Spec method has no expectations"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58292357/

相关文章:

javascript - 如何对 javascript 客户端身份验证进行单元测试

angular - 提供服务与将输入传递给组件

javascript - 通过 Angular 2 获取 native 元素相对于视口(viewport)的位置

angular - 仅在 Safari 上的 Angular ThreeJS 应用程序中的 ChunkLoadError

typescript - Express-validator 验证导致 typescript 错误 : request. query Object is possibly 'undefined'

typescript - 我如何监视 Typescript 的 getter 和 setter?

unit-testing - 您如何决定在您的测试套件中测试什么?

angular - 我的所有组件什么时候加载?

javascript - 只需稍加调整即可创建从一个对象到另一个对象的 JSON 对象

android - 访问 mObservables 时对 RecyclerView 适配器进行单元测试会引发 NullPointerException