bardjs
bardjs copied to clipboard
Mock Data Undefined
Hiya folks, I'm trying to create a unit test that checks if a GET request returns the correct amount of items, but I'm using mock data to do this.
My test looks like this:
test.js
describe('Customer Controller', function () {
var controller;
var customers = mockData.getMockCustomers(); // fake customers (5 customers)
beforeEach(function() {
bard.appModule('app');
bard.inject('$controller', '$q', '$rootScope');
var cs = {
getCustomers: function() {
return $q.when(customers);
}
};
controller = $controller('scoreListCtrl', {
CustomerService: cs
});
});
it('should return 5 customers', function() {
$rootScope.$apply();
expect(controller.customers).to.have.length(5);
});
});
I keep getting this error when I run the test:
TypeError: Cannot read property 'length' of undefined
It looks like controller.customers
is coming back as undefined
for some reason. Am I mocking the data correctly?
My controller looks like this:
function customersCtrl(dataservice) {
var vm = this;
vm.customers = [];
fetchCustomers();
function fetchCustomers() {
return dataservice.getCustomers()
.then(function(data) {
vm.customers = data.data;
return vm.customers ;
});
}
}
I've put a console.log
in the test, and my customers
variable is returning 5 objects which appear to be empty. Perhaps this is the issue?
I'm very new to this and can't work out what I'm doing wrong. I don't even know how to debug such an issue.
Any help is appreciated. Thanks in advance!
instead of expect(controller.customers).to.have.length(5);
try expect(controller.customers.length).to.equal(5);
then if you get the 'cannot get length of undefined' error, you'll know the issue is with controller.customers