Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!