jeudi 25 février 2016

Unable to unit test prototype method

I have an object, and am trying to unit test one of its methods with Jasmine.

foo.js

function Foo(value) {
  if(typeof value !== "string") {
    value = "";
  }

  var foo = {
    value: value
  };

  return foo;
};

Foo.prototype.initArr = function(arr) {
  if(arr) {
    // do nothing
  } else {
    // initialize array
    arr = [];
  }

  return arr;
};

foo.spec.js

describe("foo.js", function() {
  var validVal,
    numberVal,
    nullVal,
    falseVal,
    trueVal,
    undefinedVal;

  beforeEach(function() {
    validVal = "PrQiweu";
    numberVal = 420;
    nullVal = null;
    falseVal = false;
    trueVal = true;
    undefinedVal = undefined;
  });

  afterEach(function() {
    validVal = null;
    numberVal = null;
    falseVal = null;
    trueVal = null;
    undefinedVal = null;
  });

  describe("Foo:constructor", function() {
    it("should return an empty string if the passed value isn't a string", function() {
      var foo = new Foo(numberVal);
      expect(foo.value).toEqual("");
    });

    it("should return a string if the passed value is a string", function() {
      var foo = new Foo(validVal);
      expect(foo.value).toEqual(jasmine.any(String));
    });

    describe("method:arr", function() {

      it("should return an empty array if it wasn't passed one", function() {
        var foo = new Foo(validVal);
        expect(foo.initArr()).toBe([]);        
      });
    })
  });
});

The last test case is failing. I don't think a spy is necessary here either, but I could be wrong. I realize that the initArr function makes no sense, so please ignore my idiocy.

Why is the last test case failing, and how can I fix it?

Aucun commentaire:

Enregistrer un commentaire