Getting “Unexpected request” error when running Karma unit test in an AngularJS app

。_饼干妹妹 提交于 2019-12-06 08:13:48

Your problem is a simple, but a common one.

When you write your Jasmine / Karma unit tests, creating your controllers are almost automatic using the $controller service. That means, for the most part, you can say from your unit test

$controller('ArticleDetailCtrl')

And AngularJS will figure out its dependent services, inject them and create an instance of the controller for you to unit test.

There is one exception to this:

AngularJS does not know how to inject context specific services like $scope and $routeParams, which change based on the HTML structure and the URL for each instance of the controller.

I notice in your unit test you create the controller as

ArticleDetailCtrl = $controller('ArticleDetailCtrl', { $scope: scope });

So at this point, you tell AngularJS what object to use when the controller asks for $scope as a dependent service. But in your controller, you also inject $routeParams. And based on its articleId you create the URL for the request.

So if you change your controller instantiation code to:

ArticleDetailCtrl = $controller('ArticleDetailCtrl', { 
    $scope: scope, 
    $routeParams: articleId: ArticleId
});

That should now create the correct URL (instead of using undefined for articleId, which was the error)

Let me know if that helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!