Why `var self = this` in jasmine tests?


I’m browsing jasmine tests in the codebase and trying to learn how to properly write tests. I see many statements like var self = this. I also see that a field is accessed with this.someField sometimes and with self.someField sometimes.

Can someone explain to the reason behind this?


In short, javascript is weird. Read up on variable scoping and ‘this’: https://javascriptplayground.com/javascript-variable-scope-this/

Basically, ‘this’ refers to the current scope, so if you call a function, then inside that function ‘this’ refers to the FUNCTION’S scope not the CALLING scope. Using var self=this allows the function to access its parent scope through the variable ‘self’

1 Like

In jasmine tests, you can share values between beforeAll, beforeEach, it, afterEach, and afterAll using the function scope via the this keyword.

For example:

describe("my test", function () {
  beforeEach(function () {
    this.value = "shared via scope";

  it("should share context", function () {
    expect(this.value).toBe("shared via scope");

This is considered good practice for writing jasmine tests, as the alternative (declaring variables at the file level or inside a describe block) can lead to memory leaks and thus decreased performance when running a large number of tests.

1 Like