Angularjs 卡玛测试矿粉厂
我在angular应用程序中为lodash库创建了一个工厂,如下所示:Angularjs 卡玛测试矿粉厂,angularjs,jasmine,karma-runner,karma-jasmine,lodash,Angularjs,Jasmine,Karma Runner,Karma Jasmine,Lodash,我在angular应用程序中为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
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.\uu会中断测试,\uuu对象在测试中为空 我记得有过类似的问题。不确定问题是否完全相同,但我通过将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 _;
}
其次,我认为您应该小心测试而不是。toBe(null)
,toBeDefined()
可能更好(有很多非常精确的方法可以用Jasmine测试东西)。最后,对于第二个测试,我认为正确的测试应该是expect(typeof u.toArray).toBe('function')代码>,这比定义的代码更具体:)
我希望我回答了你的问题,即使我对单元测试的了解总体上很平淡。每次测试后,你都需要返回$window.\u
此代码应能正常工作:
describe('lodash', function() {
var factory;
// load the utilities module
beforeEach(module('lodash'));
beforeEach(inject(function (___) {
factory = ___;
}));
afterEach(inject(function (_$window_) {
_$window_._= factory;
}));
describe('_', function() {
it('should be defined', function() {
expect(factory).toBeDefined();
});
it('should have toArray() defined', function () {
expect(factory.toArray).toBeDefined();
});
it('default keys method ->', function () {
expect(factory.keys({"key1": "value1", "key2": "value2", "key3": "value3"})).toEqual(["key1","key2","key3"]);
});
});
});