Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mock Data Undefined #28

Open
realph opened this issue Nov 22, 2015 · 1 comment
Open

Mock Data Undefined #28

realph opened this issue Nov 22, 2015 · 1 comment

Comments

@realph
Copy link

realph commented Nov 22, 2015

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?

Image

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!

@shotokai
Copy link

shotokai commented Dec 2, 2015

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants