[英]Mocking Angular $window in unit test cases
I have been trying to unit test my angular custom service written in Typescript. 我一直在尝试对使用Typescript编写的角度自定义服务进行单元测试。 The service reads a global variable defined on the Window object. 该服务读取在Window对象上定义的全局变量。 I have made it promise, so that in future I can make a AJAX call to get this information. 我已经做出了承诺,以便将来我可以进行AJAX调用来获取这些信息。 Here is my stripped down service: - 这是我的精简服务: -
export class ProxyDetectiveService {
public static $inject = [
$window,
$q
];
constructor(private $window:ng.IWindowService,
private $q:ng.IQService) {
}
public getProxyUserObject = ():ng.IPromise<any> => {
this.log.debug('Proxy User Service called, to get proxy user details');
var deferred = this.$q.defer();
var proxyDetails = this.$window.portalObject;
deferred.resolve(proxyDetails);
return deferred.promise;
};
}
My unit Test Case: - 我的单位测试案例: -
describe('Proxy Detective Service - Unit Test Cases', () => {
var proxyDetectiveService:any,
$window:ng.IWindowService;
beforeEach(() => {
module('myApp');
});
beforeEach(inject(($injector:ng.auto.IInjectorService, _$window_) => {
proxyDetectiveService = $injector.get('ProxyDetectiveService');
_$window_ = {
portalObject: {
proxyUserDetails: {
firstName: 'testFN',
lastName: 'testLN'
}
}
};
}));
it('should have proxy object defined', function () {
var promise = proxyDetectiveService.getProxyUserObject();
promise.then(function (response) {
expect(response).toBeDefined();
}).catch(function (response) {
expect(response).toBeUndefined();
});
});
});
Here are my questions: - 以下是我的问题: -
My Test case gets executed, but I dont see the mocked window object in the service? 我的测试用例被执行了,但我没有看到服务中的模拟窗口对象?
My promise then or catch clause never gets executed? 我的承诺then或catch子句永远不会被执行?
Are there any better ways I can implement my service? 有没有更好的方法来实现我的服务? My intention is to return a promise, in future I may use AJAX call. 我的意图是返回一个承诺,将来我可能会使用AJAX调用。
You need to use $provide
to provide a mocked value in a unit test: 您需要使用$provide
在单元测试中提供模拟值:
beforeEach(() => {
module('myApp', ($provide) => {
$provide.value('$window', myMockedWindowObject)
});
});
You also need to call $rootScope.$apply()
to move promises forward in unit tests. 你还需要调用$rootScope.$apply()
来在单元测试中转发promises。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.