Home Blog JavaScript Sinon node.js unit testing for node-fetch
Sinon node.js unit testing for node-fetch
JavaScript
Written by Dicky   
Friday, 05 October 2018 15:26
AddThis Social Bookmark Button

Recently, I need to create unit testing for my node.js project that involved node-fetch component. For unit testing, I need to mock the return for the fetch() call.

I stumbled upon several articles that requires me to do import and using proxy to stub the call. However, what ended up working well for me is I was able to mock the fetch() by mocking the Promise method. Here's a sample:

'use strict';
const Assert = require('assert');
const sinon = require('sinon');
const nodeFetch = require('node-fetch');
const SearchProvider = require('../providers/SearchProvider');

afterEach(() => {
 sinon.restore();
});

describe('SearchProvider', function() {
 describe('getStyleGroupsFromSearch', function() {
 it('Should return 1 Stylegroup from search', async () => {
 let testInstance = new SearchProvider(null);
 let jsonObject = {"Items":[{"ChoiceBaseStyleGroupNumber": "12345"}]};
 var responseObject = {"status":'200',json: () => { return jsonObject }};
 sinon.stub(nodeFetch, 'Promise').returns(Promise.resolve(responseObject))
 var result = await testInstance.getStyleGroupsFromSearch({}, "test");

 Assert.equal(result.length, 1);
 Assert.equal(result[0], "12345");
 });
 });
});

That's because fetch() is using Promise in its code base.