gpt4 book ai didi

javascript - 在测试我的 AngularJS Controller 时,如何在 $http.get promise 中模拟结果?

转载 作者:行者123 更新时间:2023-12-03 00:01:08 26 4
gpt4 key购买 nike

经过大量阅读后,似乎从 AngularJS Controller 调用 Web 服务的推荐方法是使用工厂并从中返回 promise 。

这里我有一个简单的工厂,它调用示例 API。

myApp.factory('MyFactory', ['$http',function($http) {
var people = {
requestPeople: function(x) {
var url = 'js/test.json';
return $http.get(url);
}
};
return people;
}]);

这就是我在 Controller 中调用它的方式

myApp.controller('MyCtrl1', ['$scope', 'MyFactory', function ($scope, MyFactory) {
MyFactory.requestPeople(22).then(function(result) {
$scope.peopleList = result;
});
}]);

虽然它工作正常,但我希望能够模拟调用 then 时传入的 result 。这可能吗?

到目前为止我的尝试没有产生任何结果。这是我的尝试:

//Fake service
var mockService = {
requestPeople: function () {
return {
then: function () {
return {"one":"three"};
}
}

}
};


//Some setup
beforeEach(module('myApp.controllers'));
var ctrl, scope;

beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();

ctrl = $controller('MyCtrl1', { $scope: scope, MyFactory: mockService });
}));

//Test
it('Event Types Empty should default to false', inject(function () {
expect(scope.peopleList.one).toBe('three');
}));

我在 karma runner 中运行此程序时遇到的错误是

类型错误:“未定义”不是对象(正在评估“scope.peopleList.one”)

如何使用我的模拟数据进行此测试?

最佳答案

我不认为 $httpBackend 是你在这里追求的,你希望整个工厂被 mock 而不依赖于 $http?

看看$q ,特别是测试标题下的代码示例。您的问题可能会通过如下代码得到解决:

'use strict';

describe('mocking the factory response', function () {

beforeEach(module('myApp.controllers'));

var scope, fakeFactory, controller, q, deferred;

//Prepare the fake factory
beforeEach(function () {
fakeFactory = {
requestPeople: function () {
deferred = q.defer();
// Place the fake return object here
deferred.resolve({ "one": "three" });
return deferred.promise;
}
};
spyOn(fakeFactory, 'requestPeople').andCallThrough();
});

//Inject fake factory into controller
beforeEach(inject(function ($rootScope, $controller, $q) {
scope = $rootScope.$new();
q = $q;
controller = $controller('MyCtrl1', { $scope: scope, MyFactory: fakeFactory });
}));

it('The peopleList object is not defined yet', function () {
// Before $apply is called the promise hasn't resolved
expect(scope.peopleList).not.toBeDefined();
});

it('Applying the scope causes it to be defined', function () {
// This propagates the changes to the models
// This happens itself when you're on a web page, but not in a unit test framework
scope.$apply();
expect(scope.peopleList).toBeDefined();
});

it('Ensure that the method was invoked', function () {
scope.$apply();
expect(fakeFactory.requestPeople).toHaveBeenCalled();
});

it('Check the value returned', function () {
scope.$apply();
expect(scope.peopleList).toBe({ "one": "three" });
});
});

我已经添加了一些关于 $apply 功能的测试,直到我开始使用它之前我才知道!

高格

关于javascript - 在测试我的 AngularJS Controller 时,如何在 $http.get promise 中模拟结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17825798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com