Mock node-fetch in node.js with different scenarios

Reading Time: < 1 minutes
      
const getWithNodeFetch = async () => {
    const ops = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'OAuth [some access token]'
        }
    };
    const res = await fetch('https://example.com', ops);
    if(!res.ok) throw new Error(`error doing GET status code: ${res.status} status message ${res.statusText}`);
    return res.json();
}
   
    
      
const getFileWithNodeFetch = async () => {
    const ops = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/octet-stream',
            'Authorization': 'OAuth [some access token]'
        }
    };

    const fileFullPath = `${os.tmpdir()}/file.txt`;
    const res = await fetch('https://example.com/file.txt', ops);
    const fileStream = fs.createWriteStream(fileFullPath);

    if(!res.ok) throw new Error(`error downloading file. status code: ${res.status} status message ${res.statusText}`);

    await new Promise((resolve, reject) => {
        res.body.pipe(fileStream);
        res.body.on("error", reject);
        fileStream.on("finish", resolve);
    });
    return  {filePath: fileFullPath};

}
   
    
      
const fetch = require("node-fetch");
jest.mock('node-fetch');
      
    
      
fetch.mockReset();
fetch.mockImplementation((url, options) => {
  if (options.headers["Content-Type"] == "application/json") {
    return Promise.resolve({
      ok: true,
      status: 200,
      statusText: "ok",
      json: () => {
        return {
          name: "test",
          fileExtension: "txt",
        };
      },
    });
  } else {
    return Promise.resolve({
      ok: false,
      status: 500,
      statusText: "some error",
    });
  }
});
      
    
      
fetch.mockReset();
fetch.mockReturnValue({
    status: 500,
    statusText: "error",
    json: () => ({})
});
      
    
      
fetch.mockReset();
fetch.mockReturnValue({
    status: 404,
    statusText: "File not found",
    json: () => ({})
});
      
    
      
fetch.mockReset();
fetch.mockReturnValue({
    ok: true,
    status: 200,
    statusText: "ok",
    body: {
        pipe: () => ({}),
        on: () => ({})
    },
    json: () => {
        return {
            name: "test",
            fileExtension: "txt"
        }
    }
});
    
      
    
,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: