【问题标题】:Angular JS-Jasmine how to unit test $location.path().search()?Angular JS-Jasmine 如何对 $location.path().search() 进行单元测试?
【发布时间】:2015-04-03 10:55:51
【问题描述】:

一直在做一些谷歌搜索,但找不到我这个小问题的答案。只是试图从我的控制器测试这段代码:

$scope.viewClientAssets = (id) -> 
  $location.path("/assets").search("client_id", "#{id}") 

这反过来又返回这个网址:

http://localhost:3000/admin#/assets?client_id=19

这一切都很好,但是在单元测试时......一些假设: 我的规范设置正确,因为我有其他测试和期望工作得很好,所以这里是测试:

it 'checks if view client assets path is correct', ->
    createController()
    #gets rid of unnecessary function calls
    flushRequests()
    #calls the ctrl function with necessary args
    $scope.viewClientAssets(clientData.client.id)
    spyOn($location, 'path')
    spyOn($location, 'search') #tried diff methods here such as 
    # and.returnValue(), .calls.any(), calls.all()
    expect($location.path).toHaveBeenCalledWith("/assets")
    expect($location.path.search).toHaveBeenCalled()

所有其他测试都通过了,但是当它被击中时,我收到以下错误:

TypeError: 无法读取未定义的属性“搜索”

控制台调试器告诉我:

$scope.createClientAsset = function(id) {
        return $location.path('/assets/create').search("client_id", "" + id);
      };

那条路径未定义?

有什么想法吗?

【问题讨论】:

  • 你应该考虑改变接受的答案

标签: angularjs unit-testing jasmine


【解决方案1】:

要测试 spyOn,进行搜索,请执行以下操作

spyOn($location, 'path').and.callThrough();
spyOn($location, 'search');

这将正确返回值。

【讨论】:

  • 这是正确答案 - 应该是公认的答案 - 非常感谢 - 为我节省了很多精力:)
【解决方案2】:

你在监视$location.path 并且没有返回任何东西,或者返回 undefined。

让您的间谍返回一个字符串(您通常期望的字符串,实际路径),并且为 javascript 中的所有字符串定义的搜索功能将在您的测试中正常工作。

例如执行以下操作:

spyOn($location, 'path').and.returnValue('/client_id/')
$location.path('anything'); // returns '/client_id/'

【讨论】:

  • 我收到第二个期望语句的错误:错误:预期为间谍,但未定义。。我对这两种方法都有间谍:spyOn($location, 'path').and.returnValue('/active/'); spyOn($location, 'search'); 我的期望看起来像:expect($location.path).toHaveBeenCalledWith('/test/1'); expect($location.path.search).toHaveBeenCalled(); 我在这里做错了吗?
  • 检查expect语句中spy的名字是否正确。发布您的更新代码
  • element = angular.element('<div click-link="\'#/test/1?active=3\'">'); $compile(element)(scope); scope.$digest(); spyOn($location, 'path').and.returnValue("/active/"); spyOn($location, 'search'); element.click(); expect($location.path).toHaveBeenCalledWith('/test/1'); expect($location.search).toHaveBeenCalled();
  • 是的,您正在监视 $location.path 和 $location.search,然后检查 $location.path.search 的间谍。看到问题了吗?
  • 将其更改为 $location.search 没有帮助。它仍然给出未定义的错误。还有其他解决方案吗?
猜你喜欢
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
  • 1970-01-01
  • 2019-02-21
相关资源
最近更新 更多