typescriptpromiseasync-awaitjasminejasmine-node

Using Jasmine beforeEach asynchronously while passing this.result to test


The following code fails a unit test because this.result is still undefined. Is my issue with variable scope, asynchronous behavior, or something else I haven't thought of? My end goal is to pass this test where this.result == "somevalue"

describe("This is a test", ()=> {
  beforeEach(async ()=> {
    this.result = await "somevalue";
  })

  it("should be somevalue", async ()=> {
    await this.result;
    expect(this.result).toBe("somevalue")
  })
});

Edit: I tried the following and got it to work, however is there a way to pass this.[some variable] as we see in the Jasmine documentation for using beforeEach()?

describe("This is a test", ()=> {
  let result = undefined;
  beforeEach(async ()=> {
    result = await "somevalue";
  });

  it("should be somevalue", async ()=> {
    await result;
    expect(result).toBe("somevalue");
  })
});

Solution

  • Is this Angular?

    Try using the callback (done) function:

    describe("This is a test", ()=> {
      beforeEach(async (done)=> {
        this.result = await "somevalue";
        done();
      })
    
      it("should be somevalue", async ()=> {
        await this.result;
        expect(this.result).toBe("somevalue")
      })
    });
    

    I find this weird because I don't know what the value of this is.

    Why are we awaiting "somevalue", it is a string, nothing asynchronous about it but hopefully the done function can help you.