我正在使用AngularJS,我的测试在mocha + sinon + chai中
我要测试的代码如下所示:
addModal.result.then(function (clientFeature) {
if (clientFeature) {
//create a new $resource ClientFeature object with result
var newClientFeature = new ClientFeature(clientFeature);
//push newly created clientfeature to list
$scope.clientFeatures.push(newClientFeature);
//make REST call to create new clientfeature
newClientFeature.$save({clientId: newClientFeature.client.id}, function (data, headers) {
console.log('created.');
console.log(data);
}, null);
}
});
ClientFeature是$ resource对象:
“使用严格”;
angular.module('yrdyApp')
.factory('ClientFeature', function ($resource, $location) {
return $resource('https://' + $location.host() + ':port/clientfeatures/client/:clientId', {port: ':3333', clientId: '@clientId'}, {
update: {method: 'PUT'}
});
});
我如何模拟这一行?
//create a new $resource ClientFeature object with result
var newClientFeature = new ClientFeature(clientFeature);
我现有的模拟:
// set up mocks
ClientFeatureMock = {
query: sinon.spy(),
update: sinon.stub()
};
// mock client feature object
clientFeature = {
client: {
id: 100
},
$update: sinon.spy(),
$save: sinon.spy()
};
谢谢,肖恩
我不确定这是否是推荐的处理方式,但我决定不对服务进行存根/模拟。相反,我注入了实际的服务,并监视单个方法+设置httpBackend来拦截http请求。
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, _$timeout_, $q, $httpBackend, _ClientFeature_) {
// inject actual service
ClientFeature = _ClientFeature_;
// set up httpBackend behavior
httpBackend = $httpBackend;
httpBackend.whenGET(/https:\/\/.+\/clientfeatures\/client\/./).respond(200, []);
// set up mocks
ClientFeatureMock = {
query: sinon.spy(ClientFeature, 'query')
};
和一个示例测试:
it('should start by retrieving a list of clientfeatures for a client', function () {
// flush/make the http call
httpBackend.flush();
ClientFeatureMock.query.should.be.called;
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句