Diskdrive
Diskdrive

Reputation: 18825

How can I get jasmine to mock values of arrays?

I'm using this library at the moment to try to get Handlebars working on the server side of my meteor app (https://github.com/EventedMind/iron-router#using-a-layout-with-yields).

I've gotten it to work but I now want to fix my unit test. I'm a bit of a beginner at Jasmine so hopefully this question isn't too stupid. Tell me if I'm completely on the wrong track.

At the moment I'm trying to mock this line in a jasmine unit test.

Handlebars.templates['ResponseToSubscribers']({dateSent: new Date()})

I know how to mock methods, but I'm not sure how to mock array values.

I've tried doing this.

spyOn(Handlebars, 'templates').andReturn({"ResponseToSubscribers": (obj) -> "html"})

but it's giving me this error.

templates() method does not exist

How can I mock [] and get it return something?

Upvotes: 2

Views: 3490

Answers (1)

user3037143
user3037143

Reputation: 926

A small correction to the way of adding a spy will solve the problem. Spy registration has to be done to the object and function/value on that object. Modifying the registration to spyOn(Handlebars.templates, 'ResponseToSubscribers') will solve your problem.

Sample Code:

describe("Test Array", function() {
it("checks the actual value", function() {
    var t1 = Handlebars.templates['ResponseToSubscribers']('dummy');
    expect(t1).toEqual(1);
});

it("checks handle bar value", function() {
    spyOn(Handlebars.templates, 'ResponseToSubscribers').and.returnValue(2);
    var t = Handlebars.templates['ResponseToSubscribers']('dummy');
    expect(t).toEqual(2);
});
});

Upvotes: 3

Related Questions