dimanche 5 juillet 2015

Jasmine: Testing a function that uses a browser object

I am trying to test this function with Jasmine:

myFunc: function () {
  var name = document.getElementById("bob");
  display.innerHTML = name;
  return 100;
}

The test fails with ReferenceError: document is not defined. I understand that I'm not running the test in a browser so document isn't defined. But how come mocking it out isn't working? Is there a way to write this test with standalone Jasmine only?

How would one generally go about testing these kinds of functions (JavaScript mixed with DOM)? I'd prefer not to use another library/framework.

// Mock, stub dom object.
var document;
  beforeEach(function () {
  document = jasmine.createSpyObj('document', ['getElementById', 'createElement']);
});

describe("myFunc", function () {    
  it("return 100", function () {
    console.log(document);         // My mock document object successfully logs.
    expect(myFunc()).toEqual(100); // but document isn't defined in here.
  });
});

Aucun commentaire:

Enregistrer un commentaire