اختبار الكارما مع .success() الحصول على "غير محدد" ليس كائنًا"
-
21-12-2019 - |
سؤال
أحاول كتابة اختبار وحدة لمعرفة ما إذا كان سيتم استدعاء وظيفة الموفر "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;
});
}
};
يبدو اختبار وحدة الكارما الخاص بي كما يلي:
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", "");
});
});
});
});
عندما أقوم بتشغيل هذا، أحصل على الخطأ التالي:
TypeError: 'undefined' is not an object (evaluating 'StudentsProvider.getStudents($scope.keyword, $scope.selectedFilters).success')
وربما يكون ذلك لأنني لا أسخر من رد الاتصال .success().كيف لي أن افعل ذلك؟شكرا لك مقدما!
المحلول
استبدل هذا:
var mockStudentsProvider = {
getStudents: function getStudents() {
return [{
Education: [],
Person: [{
ID: 1,
Name: "Testing McTestsson",
SSN: "1234567890",
Address: "Fakestreet 3",
MobilePhone: "7777777"
}]
}];
}
};
مع هذا:
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)
};
}
}
};
واستبدل هذا:
spyOn(StudentsProvider, 'getStudents');
مع هذا:
spyOn(StudentsProvider, 'getStudents').andCallThrough();
عندما لا تستخدم
andCallThrough()
أوandCallFake()
يمنع الياسمين تنفيذ الطريقة ويعيد القيمة فارغة.داخل طريقة التحديث الخاصة بك الذي تتصل بهnull.success
.هذا سوف يفشل.(http://jasmine.github.io/1.3/introduction.html)في طريقتك الوهمية، تحتاج إلى تغيير تنسيق الإرجاع - تقوم طريقة http الحقيقية بإرجاع كائن حيث يشير النجاح إلى وظيفة تأخذ مدخلاً وظيفة رد اتصال.
في حالتك، وظيفة رد الاتصال هي:
function(data) {
$scope.students = data;
}