AngularM AngularM - 1 year ago 153
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,


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);



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

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:

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

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

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download