我已经在我的角度应用程序中为lodash库创建了一个工厂,如下所示:
angular.module('lodash',[]).service('_', function(){
var _ = window._;
// i am delete the _ property on the window
// so that i m enforced to dependency inject
// lodash each time i want to use it
// instead of using the global lodash library
delete window._;
return _;
});
现在我想使用以下测试来测试我的模块服务和即时消息
describe('lodash', function() {
// load the utilities module
beforeEach(module('lodash'));
describe('_', function() {
it('should be defined', inject(function(_) {
expect(_).not.toBe(null);
}));
it('should have toArray() defined', inject(function(_) {
expect(_.toArray).toBeDefined();
}));
});
});
此第二次测试未成功。进行这项工作的唯一方法是从我的服务实现中删除以下内容。
delete window._;
我的问题是:由于delete运算符仅从window对象中删除属性,而不是原始引用,因此为什么删除window._会破坏测试,并且_对象在测试中为空?
我记得有类似的问题。不知道问题是否完全相同,但我解决了将lodash的属性复制到新对象中的问题,然后我从工厂返回了该对象:
function lodash($window) {
var lodashLib = $window._;
var _ = {};
delete( $window._ );
// Instead of using directly what I got from the window object, I copy its properties
// I cannot explain why this works better, but it solved the problem for me
angular.extend(_, lodashLib);
return _;
}
其次,我认为您应该谨慎进行测试not.toBe(null)
,toBeDefined()
可能会更好(有很多非常精确的方法可以使用Jasmine测试事物)。最后,对于您的第二个测试,我认为正确的测试应该是expect(typeof _.toArray).toBe('function');
,这比刚刚定义的要具体得多:)
我希望我回答了您的问题,即使我对单元测试的了解总体上还很乏味。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句