問題描述
我在對以下方法進行單元測試時遇到問題:
I'm having a problem unit testing the following method:
$scope.changeLocation = function (url) {
$location.path(url).search({ ref: "outline" });
};
我編寫了以下單元測試,但當前失敗并出現此錯誤(TypeError: Cannot read property 'search' of undefined):
I've written the following unit test that currently fails with this error (TypeError: Cannot read property 'search' of undefined):
var $locationMock = { path: function () { }, search: function () { } };
it('changeLocation should update location correctly', function () {
$controllerConstructor('CourseOutlineCtrl', { $scope: $scope, $location: $locationMock });
var url = "/url/";
spyOn($locationMock, "path");
spyOn($locationMock, "search");
$scope.changeLocation(url);
expect($locationMock.search).toHaveBeenCalledWith({ ref: "outline" });
expect($locationMock.path).toHaveBeenCalledWith(url);
});
如果我將函數更改為以下,則測試通過:
If I change my function to the following, the test passes:
$scope.changeLocation = function (url) {
$location.path(url);
$location.search({ ref: "outline" });
};
當我使用方法鏈接時,如何對這個方法進行單元測試?我需要以不同的方式設置我的 $locationMock 嗎?對于我的生活,我無法弄清楚這一點.
How do I unit test this method when I'm using method chaining? Do I need to setup my $locationMock differently? For the life of me I cannot figure this out.
推薦答案
那是因為你的 mock 沒有返回 location 對象以便能夠鏈接.使用 Jasmine 2.0,您可以將模擬更改為:
That is because your mock does not return location object to be able to chain through. Using Jasmine 2.0 you can change your mock to:
var $locationMock = { path: function () { return $locationMock; },
search: function () { return $locationMock; } };
和
spyOn($locationMock, "path").and.callThrough();
spyOn($locationMock, "search").and.callThrough(); //if you are chaining from search
或添加:
spyOn($locationMock, "path").and.returnValue($locationMock);
spyOn($locationMock, "search").and.returnValue($locationMock); //if you are chaining from search
或者只是創建一個間諜對象(更少的代碼):
Or just create a spy object (less code):
var $locationMock = jasmine.createSpyObj('locationMock', ['path', 'search']);
和
$locationMock.path.and.returnValue($locationMock);
$locationMock.search.and.returnValue($locationMock); //if you are chaining from search
這篇關于如何使用 Jasmine 對鏈式方法進行單元測試的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!