Bja*_*rki 5 unit-testing angularjs karma-runner
我正在尝试编写一个单元测试,看看如果适当设置某些属性,我的控制器中的'getStudents()'提供程序函数是否会被调用.注意.success()回调:
$scope.update = function update() {
// omitted, just doing some checking...
// finally
else if (key.length === 3 || $scope.students.length === 0) {
StudentsProvider.getStudents($scope.keyword, $scope.selectedFilters).success(function(data) {
$scope.students = data;
});
}
};
Run Code Online (Sandbox Code Playgroud)
我的业力单元测试看起来像这样:
describe("Students: Controllers", function () {
var $scope;
var ctrl;
beforeEach(module('studentsApp'));
describe("SearchCtrl", function () {
// Mock the provider
var mockStudentsProvider = {
getStudents: function getStudents() {
return [
{
Education: [],
Person: [{
ID: 1,
Name: "Testing McTestsson",
SSN: "1234567890",
Address: "Fakestreet 3", MobilePhone: "7777777"
}]
}
];
}
};
var StudentsProvider;
beforeEach(inject(function ($controller, $rootScope) {
$scope = $rootScope.$new();
ctrl = $controller('SearchCtrl', { $scope: $scope, StudentsProvider: mockStudentsProvider});
StudentsProvider = mockStudentsProvider;
}));
describe("Update", function () {
beforeEach(function () {
spyOn(StudentsProvider, 'getStudents');
});
it("should always call the provider with 3 letters", function () {
$scope.keyword = "axe";
$scope.update();
expect(StudentsProvider.getStudents).toHaveBeenCalled();
expect(StudentsProvider.getStudents).toHaveBeenCalledWith("axe", "");
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我收到以下错误:
TypeError: 'undefined' is not an object (evaluating 'StudentsProvider.getStudents($scope.keyword, $scope.selectedFilters).success')
Run Code Online (Sandbox Code Playgroud)
这可能是因为我没有嘲笑.success()回调.我该怎么办?提前致谢!
替换这个:
var mockStudentsProvider = {
getStudents: function getStudents() {
return [{
Education: [],
Person: [{
ID: 1,
Name: "Testing McTestsson",
SSN: "1234567890",
Address: "Fakestreet 3",
MobilePhone: "7777777"
}]
}];
}
};
Run Code Online (Sandbox Code Playgroud)
有了这个:
var mockStudentsProvider = {
getStudents: function getStudents() {
var retVal = [{
Education: [],
Person: [{
ID: 1,
Name: "Testing McTestsson",
SSN: "1234567890",
Address: "Fakestreet 3",
MobilePhone: "7777777"
}]
}];
return {
success: function(fn) {
fn(retVal)
};
}
}
};
Run Code Online (Sandbox Code Playgroud)
并替换这个:
spyOn(StudentsProvider, 'getStudents');
Run Code Online (Sandbox Code Playgroud)
有了这个:
spyOn(StudentsProvider, 'getStudents').andCallThrough();
Run Code Online (Sandbox Code Playgroud)
当您不使用andCallThrough()或andCallFake()jasmine阻止执行该方法并返回null.在你正在调用的更新方法中null.success.这将失败.(http://jasmine.github.io/1.3/introduction.html)
在你的mock方法中,你需要改变返回格式 - 真正的http方法返回一个对象,其中success指的是一个输入回调函数的函数.
在您的情况下,回调函数是:
function(data) {
$scope.students = data;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4062 次 |
| 最近记录: |