I'm currently working on writing unit tests for an Angular application using Jasmine, specifically focusing on testing different scenarios within a function. The main challenge I am facing is structuring the test to accommodate various conditions such as the if statement and callbacks.
The $scope function in question takes an Object as input. If the object contains an id
, it updates the existing object. Otherwise, it creates a new report and sends it to the backend using the CRUD
service.
$scope.saveReport = function (report) {
if (report.id) {
CRUD.update(report, function (data) {
Notify.success($scope, 'Report updated!');
});
} else {
CRUD.create(report, function (data) {
$scope.report = data;
Notify.success($scope, 'Report successfully created!');
});
}
};
One of my tests involves passing a mock Object with an id
to trigger the CRUD.update
method, which I then verify has been called.
describe('$scope.saveReport', function () {
var reports, testReport;
beforeEach(function () {
testReport = {
"id": "123456789",
"name": "test"
};
spyOn(CRUD, 'update');
$scope.saveReport(testReport);
});
it('should call CRUD factory and update', function () {
expect(CRUD.update).toHaveBeenCalledWith(testReport, jasmine.any(Function));
});
});
While I understand that Jasmine does not support multiple spies, I still want to find a way to test the if condition and also create a mock test when the Object does not include an id
:
describe('$scope.saveReport', function () {
var reports, testReport;
beforeEach(function () {
testReport = {
"id": "123456789",
"name": "test"
};
testReportNoId = {
"name": "test"
};
spyOn(CRUD, 'update');
spyOn(CRUD, 'create'); // TEST FOR CREATE (NoId)
spyOn(Notify, 'success');
$scope.saveReport(testReport);
$scope.saveReport(testReportNoId); // TEST FOR NO ID
});
it('should call CRUD factory and update', function () {
expect(CRUD.update).toHaveBeenCalledWith(testReport, jasmine.any(Function));
// UNCERTAIN ABOUT THIS PART AS WELL
});
});
I have read about using the .andCallFake()
method but unclear on how to apply it in my specific case. Any guidance would be greatly appreciated.