我需要对覆盖$ windowProvider的自定义提供程序进行单元测试。
provider.js
angular
.module('customProvider', [])
.provider('cprovider', [
'$windowProvider',
function ($windowProvider) {
var $window = $windowProvider.$get();
var platform = function () {
// some code there use $window
};
this.platform = platform;
this.$get = function () {
return {
platform: platform
};
};
}
]);
cprovider.spec.js
describe('cprovider', function () {
var cprovider, mockWindow;
describe("xxxx", function () {
beforeEach(function () {
mockWindow = {navigator: {userAgent: 'xxxx'}};
module('customProvider', function ($provide) {
$provide.value('$window', 'mockWindow');
});
inject(function (_cprovider_) {
cprovider = _cprovider_;
});
});
it('should something', function () {
// Arrange and Act in beforeEach.
// Assert. WON'T WORK
expect(cprovider.platform()).toBe('xxx');
});
});
});
无法正确模拟$ windowProvider。 任何人都知道我该怎么做?
答案 0 :(得分:4)
你可以窥探$ window:
beforeEach(function () {
angular.mock.module('customProvider');
inject(function (_$window_, _cprovider_) {
cprovider = _cprovider_;
$window = _$window_;
spyOn($window, 'alert');
});
});
完整小提琴here