AngularM AngularM - 4 months ago 43
AngularJS Question

Angular directive unit test issue when passing data into the directive for testing

Angular directive unit test issue when passing data into the directive for testing.

I'm having trouble when I pass a data object into the directive.

I get the following error: "Syntax Error: Token 'Object' is unexpected, expecting []] at column 9 of the expression [[object Object]] starting at [Object]]"

This is my unit test:

describe("Pagination:", function () {

var element,
scope,
mockData,
rootScope;

beforeEach(angular.mock.module("myApp"));

beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope.$new();

//Seems to be an issue here:
mockData = {
data: [],
meta: {},
links: {}
};

element = "<pagination data=\"" + mockData + "\"></pagination>";
element = $compile(element)(scope);

angular.element(document.body).append(element);

scope.$digest();
}));

it("should emit for more data when get data is called", function () {
sinon.stub(scope, "$emit");
scope.getData("dummyUrl");

expect(scope.$emit.calledWith("pagination:getTabPage", "dummyUrl")).toEqual(true);
});
});


The test seems fine.
Just seems to be an issue with the setup of the test.


This is the html:

<pagination data="data"></pagination>


This is the directive I'm looking to test:

angular.module("myApp")
.directive("pagination", [function() {
return {
restrict: "E",
scope: {
data: "="
},
templateUrl: "pagination.html",
link: function(scope) {
scope.totalPages = scope.data.meta["total-pages"];

scope.getData = function(pageUrl) {
if (pageUrl !== null) {
scope.$emit("pagination:getTabPage", pageUrl);
}
};
}
};
}]);

Answer

The value for mockData needs to be encoded prior to being joined into a string.

element = "<pagination data=\"" + angular.toJson(mockData) + "\"></pagination>";

The other option would be to simply add the mockData object as a property on the scope and reference that in the HTML that you are compiling in your test.

scope.mockData = { … };
element = "<pagination data='mockData'></pagination>";
element = $compile(element)(scope);