我的任务是为一些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,我将测试该方法,只是它被称为我已经编写了代码来测试简单的函数,但是没有像这样的函数,所以任何帮助都会非常感激,我今天下午的大部分时间都在试图弄明白
答案 0 :(得分:3)
您可以使用jasmine来模拟您不想测试的函数调用。例如,你可以告诉jasmine每次都返回一个空数组" populateCallAlertOnEditCall'叫做。我将写一个可能给你一个见解的例子:
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.
}));
});
答案 1 :(得分:1)
测试某事已被调用,您可以使用Spy
你的断言看起来像:
spyOn(obj, 'populateCallAlertOnEditCall')
expect(obj.method).toHaveBeenCalled()
更新:
populateCallAlertOnEditCall = {}
spyOn(obj, 'populateCallAlertOnEditCall.result')
expect(obj.method).toHaveBeenCalled()
答案 2 :(得分:1)