我的任务是为一些AngularJS代码编写单元测试,这些代码是由另一个没有编写任何测试的团队编写的
他们编写了以下功能,但我无法弄清楚如何测试它
function showCallAlerts(callRecord, isInEditMode, callBack) {
var callAlerts = populateCallAlertOnEditCall(callRecord.callAlert);
var callModalInstance = openAlertModalInstance('Call', callAlerts, callBack);
if (callModalInstance !== undefined && callModalInstance !== null) {
callModalInstance.result.then(function() {
// Show equipment alerts based on company details
showEquipmentAlertsBasedOnCompanyDetails(callRecord, isInEditMode, callBack);
});
} else {
// Show equipment alerts based on company details
showEquipmentAlertsBasedOnCompanyDetails(callRecord, isInEditMode, callBack);
}
}
我需要测试每个函数都被调用,不要担心它们的作用,因为我将它们分开测试,只是它们被调用。
当调用populateCallAlertOnEditCall时,它需要返回一个空数组或一个包含一些项的数组
当调用openAlertModalInstance时,它需要返回undefined或者传递给showEquipmentAlertsBasedOnCompanyDetails的内容
应该实际调用showEquipmentAlertsBasedOnCompanyDetails,我会将该方法分开测试,只是调用它
我已经设法编写代码来测试简单的功能,但没有像这样的任何帮助将非常感激,我今天下午的大部分时间都试图弄明白
测试某事已被调用,你可以使用Spy
你的断言看起来像:
spyOn(obj, 'populateCallAlertOnEditCall')
expect(obj.method).toHaveBeenCalled()
更新:
populateCallAlertOnEditCall = {}
spyOn(obj, 'populateCallAlertOnEditCall.result')
expect(obj.method).toHaveBeenCalled()
您可以使用jasmine来模拟您不想测试的函数调用。例如,每次调用'populateCallAlertOnEditCall'时,都可以告诉jasmine返回一个空数组。我将写一个可能给你一个见解的例子:
describe('My Test Spec', function() {
var myController;
...
beforeEach( inject(($controller) => {
myController = $controller("myControllerName");
}));
it('Testing showCallAlerts when populateCallAlertOnEditCall returns an empty array', inject(function($controller) {
//setup
//this will replace every call to populateCallAlertOnEditCall with
//the function inside callFake
spyOn(myController, 'populateCallAlertOnEditCall ').and.callFake(function() {
return []; //returning an empty array.
});
//action
myController.showCallAlerts(...);
//assert
//Do your checking here.
}));
it('Testing showCallAlerts when populateCallAlertOnEditCall returns a non-empty array', inject(function($controller) {
//setup
//this will replace every call to populateCallAlertOnEditCall with
//the function inside callFake
spyOn(myController, 'populateCallAlertOnEditCall ').and.callFake(function() {
return [1,2,3,4]; //returning a non-empty array.
});
//action
myController.showCallAlerts(...);
//assert
//Do your checking here.
}));
});