Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jasmine: scope of this

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?

like image 227
Johannes Avatar asked Sep 29 '22 12:09

Johannes


1 Answers

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.

like image 156
John-M Avatar answered Oct 03 '22 10:10

John-M