简体   繁体   中英

How would you test a method that returns a promise using Jest

I would like to know how a method that returns a promise that resolves another method can be tested with jest.

For example:-

    getUser() {
    const getListFromDatabase= this.getListFromDatabase.bind(this);
    const getListFromUser= this.getListFromUser.bind(this);
    return new Promise((resolve) => {
      const myList = Cookies.get('myList');
      if (myList) {
        resolve(myList);
      } else if (CONFIGURATION.ENABLED) {
        resolve(getListFromDatabase());
      } else {
        resolve(getListFromUser());
      }
    });
  },

getListFromDatabase and getListFromUser are other methods in my main object.

getUser() is a method in my main object.

So now I want to write a unit test with jest that would test that we resolved an array (myList) if the cookie was found, we resolved getListFromDatabase() if the global configuration variable was enabled or else getListFromUser() .

The fact that I return a new promise that resolves makes me confused which way to go, with expect().resolves or getUser().then(data => expect(data)..)

you can use flush-promises to make the promises resolve, then you don't need to wait for the promise.

example :

test('flushPromises', async () => {
  let a;
  let b;

  Promise.resolve().then(() => {
    a = 1;
  }).then(() => {
    b = 2;
  })

  await flushPromises();

  expect(a).toBe(1);
  expect(b).toBe(2);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM