5
votes

From the jasmine documentation (http://jasmine.github.io/2.0/introduction.html):

The this keyword

Another way to share variables between a beforeEach, it, and afterEach is through the this keyword. Each spec’s beforeEach/it/afterEach has the this as the > same empty object that is set back to empty for the next spec’s beforeEach/it/afterEach.

My understanding of this in Javascript is, that this is bounded to the scope of the actual function. So I would expect that it would be bound to the context different contexts (the ones depending on the function) inside beforeEach/it/afterEach.

e.g.

describe('Spec', function (){
  var eachThis = null;
  beforeEach(function(){
    eachThis = this;
  });
  it('check this', function(){
    except(this).toEqual(eachThis);
  }
};

So this test should pass.

Did jasmine change the behavior of this or did i get something wrong?

2

2 Answers

4
votes

I think your example maybe has some issues, but you are correct in thinking that jasmine manipulates the this reference when using beforeEach, beforeAll, etc.

Here is an illustrative example -- note that all of the expects listed below will pass:

(function() {
  describe("without beforeEach", function () {
    (function() {
      // this is not inside of a beforeEach call
      this.dog = "Spot";
      alert(this.dog);
    })();
    it("should not have access to a dog property from `this`", function () {
        expect(this.dog).toBeUndefined(); // because there is no `dog` member of the object currently referenced by `this`
    });
  });

  describe("a beforeEach test", function () { 
    beforeEach(function () {
        this.dog = "Spot";
    });
    it("should work now because we used `beforeEach`", function () { 
        expect(this.dog).toEqual("Spot");
    });

  });
})();

In general, your thinking about 'this' being defined within the scope of function is correct, but this implementation in jasmine demonstrates how you can provide a specific object to be referenced by the 'this' keyword if you want to. The typical way this is done in javascript is using Function.prototype.apply() which allows you to pass in an arbitrary object for the this reference as the first parameter of the function.

0
votes

So this test should pass.

Yes, and it does.

Did jasmine change the behavior of this

It doesn't look like it.

did i get something wrong

You have syntax errors and typos in your code (e.g. except -> expect).


Also, toEqual doesn't test the identity of an object, so even expect(this).toEqual({}); would pass. toBe is a better method here.