Skip to content

Mock Data Undefined #28

Description

@realph

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!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions