简体   繁体   中英

Unit testing async function with callback

Trying to write unit tests for reading a json file with the readFile function however I get the error: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout. I must be doing something wrong when mocking the json file.

The function:

function jsonReader(filePath, cb) {
  fs.readFile(filePath, (err, fileData) => {
    if (err) {
      return cb && cb(err);
    }
    try {
      const object = JSON.parse(fileData);
      return object;
    } catch (err) {
      return cb && cb(err);
    }
  });
}
module.exports = jsonReader;

Then the testfile:

const jsonReader = require('.././ReadJson');
jest.mock('fs', () => {
  const MOCK_FILE_INFO = { 'test.json': JSON.stringify({ name: 'myname' }) };
  return {
    readFile: (fpath, opts) => {
      if (fpath in MOCK_FILE_INFO) {
        return MOCK_FILE_INFO[fpath];
      }
    }
  };
});


test('Test file', (done) => {
  function callback(data) {
    expect(data.name).toBe('myname');
    done();
  }

  jsonReader('test.json', callback);
});

I tried to change the timeout but if I put it higher the execution also takes longer and it's still giving the same error.

You're trying to use your functions synchronously?

jest.mock('fs', () => {
  const MOCK_FILE_INFO = { 'test.json': JSON.stringify({ name: 'myname' }) };
  return {
    readFile: (fpath, callback) => {
      if (fpath in MOCK_FILE_INFO) {
        callback(null, MOCK_FILE_INFO[fpath]);
      }
    }
  };
});
function jsonReader(filePath, cb) {
  fs.readFile(filePath, (err, fileData) => {
    if (err) {
      return cb && cb(err);
    }
    try {
      const object = JSON.parse(fileData);
      cb(object);
    } catch (err) {
      return cb && cb(err);
    }
  });
}
module.exports = jsonReader;

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