【发布时间】:2014-05-02 14:53:52
【问题描述】:
假设您有一个显示地点列表的 Angular 应用。有一个按钮可以获取您当前的位置,单击该按钮会根据与您所在位置的距离对列表进行排序,最近的在前。
要在 Protractor 中进行测试,您希望能够单击按钮并检查列表:
it('Should order items according to distance', function () {
locButton.click();
expect(...).toBe(...); // Check that the first item on the list
// the closest to the given lat/long
});
现在,假设按钮调用控制器中的方法,控制器调用服务中的方法,服务调用 navigator.geolocation.getCurrentPosition()(并且,为了更好的衡量,该调用被包装在一个承诺中)。对此进行测试的最佳方法是模拟对 getCurrentPosition() 的调用并返回特定的纬度和经度,这样就可以一直返回到页面输出链的所需效果。你如何设置那个模拟?
我尝试了this answer to a similar question about Jasmine中的方法,在navigator.geolocation上创建了一个spy,结果:
ReferenceError: navigator is not defined
我还尝试使用类似于this answer 的内容来模拟服务,结果是:
ReferenceError: angular is not defined
更新: 找到了一个解决方案,所以我在下面回答了我自己的问题,但我真的非常希望有比这更好的答案。
【问题讨论】:
标签: angularjs unit-testing mocking protractor