简体   繁体   中英

Testing file read wtih fs using JEST

I am trying to test the following function:

async function read () {
  return new Promise(function(resolve, reject) {
    fs.readFile("INVALID_PATH", (err, contents) => {
      if (err) {
        reject(new Error('ERROR'));
      }
      resolve(contents);
    });
  });
}

through the test:

try {
  await read();
} catch (e) {
  expect(e).toMatch('ERROR');
}

However, I can't catch the rejection on catch, it gives me timeout.

Any suggestions?

EDIT:

I managed to get it working by using a mock, this way:

try {
  fs.readFile.mockReset()
  fs.readFile.mockImplementation((path, options, cb) => {
    cb('ERROR')
  })

  await readFile()

} catch (err) {
  expect(err).toBe('ERROR')
}

However, I still don't understand why this is necessary...

Have you tried declaring the test function as async in Jest? await cannot be used outside async functions (or in top level code), you have to do something like this:

it('works with async/await', async () => {
  expect.assertions(1);
  const data = await user.getUserName(4);
  expect(data).toEqual('Mark');
});

// async/await can also be used with `.resolves`.
it('works with async/await and resolves', async () => {
  expect.assertions(1);
  await expect(user.getUserName(5)).resolves.toEqual('Paul');
});

More info for testing async/await in jest https://jestjs.io/docs/en/tutorial-async.html

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