How do you write a Jest test to check if code execution is blocked?

Viewed 140

I am using async-mutex I just want to test a functionality for it specifically I want to confirm whether the Mutex.acquire method keeps things blocked.

it('should remain blocked when accessing the mutex a second time', async () => {
    const mutex = new Mutex();
    const release = await mutex.acquire();
    expect(mutex.isLocked()).toBeTruthy();

    expect( async () => { await mutex.acquire() } ).toStillBeRunningAfterSpecifiedSeconds(5);
  });

I tried

expect(await mutex.acquire()).toThrow("Timeout");

Since I get this message

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:

but no luck.

1 Answers

This is one way you could do it:

describe("async-mutex", () => {
  it("checks that lock is released", (done) => {
    const mutex = new Mutex();

    // releases the lock right after locking it
    mutex.acquire().then((release) => {
      release();

      expect(mutex.isLocked()).toBe(false);

      done();
    });
  });

  it("checks that lock is not released", (done) => {
    // if test is running after 4 seconds, then mutex is still locked
    // done exits this test without errors
    setTimeout(() => {
      done();
    }, 4000);

    const mutex = new Mutex();

    mutex.acquire();

    expect(mutex.isLocked()).toBe(true);

    // this second call to acquire should never run
    // if it does, then the test should fail
    mutex.acquire().then(() => {
      expect(1).toBe(2);
    });
  });
});

Now, if you problem is with the duration of the test, you can always increase it using jest.setTimeout(milliseconds).

Related