【发布时间】:2014-10-29 20:15:49
【问题描述】:
我正在使用 Mocha 和 Sinon 来测试我的 Angular 应用程序。我在将间谍用于返回承诺的方法时遇到问题。这是我的测试:
describe('product model', function() {
'use strict';
var mockProductsResource, Product;
beforeEach(function() {
module('app.models')
mockProductsResource = {
all: sinon.spy(),
find: sinon.spy(),
create: sinon.spy()
};
module(function($provide) {
$provide.value('productsResource', mockProductsResource);
})
inject(function($injector) {
Product = $injector.get('Product');
})
});
describe('module', function() {
// THE TEST THAT IS FAILING
it('should find one record', function() {
Product.find(1);
expect(mockProductsResource.find).to.should.have.been.calledOnce;
});
});
});
当它运行时我得到
TypeError: 'undefined' 不是一个对象(评估 'productsResource.all().then')
因为我对 productsResource.all() 的间谍没有返回承诺,而我正在测试的使用 productsResource.all() 的代码期望:
angular.module('app.models').factory('Product', ['productsResource', function(productsResource) {
// Constructor function for models
function Product(attributes) {
// ...
}
// Public "instance" methods for models
Product.prototype.update = function() {
// ...
};
Product.prototype.save = function() {
// ...
};
Product.prototype.remove = function() {
// ...
};
// Public "class" methods for this factory
// THE METHOD I AM TESTING
function all() {
return productsResource.all().then(function(response) {
var products = [], index;
for (index in response.data) {
products.push(new Product(response.data[index]));
}
return products;
});
}
function find(id) {
return productsResource.find(id).then(function(response) {
return new Product(response.data);
});
}
function create(attributes) {
return productsResource.create(attributes);
}
return {
all: all,
find: find,
create: create
};
}]);
任何想法如何使用间谍并使这个测试工作?
【问题讨论】: