AngularJS 服务测试 (Jasmine/Karma) - 错误 : Unexpected request: GET

标签 angularjs unit-testing jasmine

我目前正在尝试测试我使用 Karma 和 Jasmine 编写的 AngularJS 服务。但是,我目前遇到了 $httpBackend 的问题,并且无法解决它。这是我的服务和测试:

服务:

export default angular.module("api:events", [])
.factory("Events", ($http) => {
    let api = "http://localhost:5000/api/";
    let Events = {};

    Events.query = (params) => {
        return $http.get(`${api}/events`, {params: params}).then((res) => {
            return res.data;
        });
    };

    Events.get = (params) => {
        return $http.get(`${api}/events/` + params.id).then((res) => {
            return res.data;
        });
    };

    return Events;
});

测试:

describe("api:events", () => {
    let EventsFactory, $scope, http;

    beforeEach(module("app"));

    beforeEach(inject((_Events_, $rootScope, $httpBackend) => {
        EventsFactory = _Events_;
        $scope = $rootScope.$new();
        http = $httpBackend;
    }));


    it("should return an object", () => {
        let data = {};
        let url = "http://localhost:5000/api/events/:id";
        let response = { id: "12345" };

        http.whenGET(url).respond(200, response);

        data = EventsFactory.get({ id: "1"});

        expect(data).not.toEqual("12345");

        http.flush();

        expect(data).toEqual("12345");

        http.verifyNoOutstandingExpectation();
        http.verifyNoOutstandingRequest();
    });
});

我收到的错误(由于 http.flush()):

Chrome 46.0.2490 (Mac OS X 10.10.5) api:events test FAILED
    Error: Unexpected request: GET http://localhost:5000/api/events/1
    No more request expected

如果我在 data = EventsFactory.get({ id: "1"}); 之后记录数据,我会得到 Object{$$state: Object{status: 0}}.

我也尝试过这样调用我的服务,结果类似:

EventsFactory.get({ id: "1"}).then((result) => {
    data = result;
});

有什么想法吗?

最佳答案

这里的问题是,提供给 $http 模拟的 whenXXX()expectXXX() 方法的 URL 必须是文字。人们可能直观地期望带有参数的 URL(例如问题代码中的 :id)会起作用,但事实并非如此。因此,要纠正错误,只需替换:

let url = "http://localhost:5000/api/events/:id";

与:

let url = "http://localhost:5000/api/events/1"; // `1` is the literal id

关于AngularJS 服务测试 (Jasmine/Karma) - 错误 : Unexpected request: GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33331727/

相关文章:

javascript - 用于处理 HTTP 错误状态的 Angular JS 拦截器

c# - 模拟单元测试 - 获取实现接口(interface)的类的详细信息

c# - 尝试创建最小起订量对象

unit-testing - Angular 2 Jasmine 无法绑定(bind)到 'routerLink',因为它不是 'a' 的已知属性

javascript - 睾丸错误: Cannot start chrome

angularjs - 从 Angular 1.0 升级到 Angular 1.3.2 的主要挑战是什么

angularjs - 引导一个 Angular 2 应用程序,与一个已经加载的 Angularjs 应用程序并排

javascript - 如何在 View 中显示JS对象

android - Android 4.2 上的加密错误

AngularJS karma 过滤器未知提供者