Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to test promise before it runs finally with JEST

I have a function like this:

let settings = {
  isRun: false
}
function testPromise(promise) {
  settings.isRun = true;
  return promise.finally(() => settings.isRun = false;)
}

How can test isRun = true when run testPromise before finally expression run. I tried with

it('should isRun true when testPromise running', async () => {
   expect(settings.isRun).toBeFalsy();
   await testPromise(Promise.resolve('run')).then(() => {
     expect(settings.isRun).toBeTruthy();
   }
   expect(settings.isRun).toBeFalsy();

but it does not work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you can execute but not wait for the promise to observe the intermittent value change you want to see.

it('should isRun true when testPromise running', () => {
    expect(settings.isRun).toBeFalsy();
    const promise = testPromise(Promise.resolve('run'));
    // At this point, promise is not resolved yet, so the callback in finally has not executed yet.
    expect(settings.isRun).toBeTruthy();
    // If you want to test it changed back to fasle
    promise.then(() => {
        expect(settings.isRun).toBeFalsy();
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading