Testing: mocking node-fetch dependency that it is used in a class method
ava, sinon, stub, testing
Solution
Finally I resolved this problem stubbing the `fetch.Promise` reference like this:
sinon.stub(fetch, 'Promise').returns(Promise.resolve(responseObject))
the explanation for this it's that `node-fetch` have a reference to the native Promise and when you call `fetch()`, this method returns a `fetch.Promise`.
Problem
I have the following situation: A.js ``` import fetch from 'node-fetch' import httpClient from './myClient/httpClient' export default class{ async init(){ const response = await fetch('some_url') return httpClient.init(response.payload) } } ``` A_spec.js ``` import test from 'ava' import sinon from 'sinon' import fetch from 'node-fetch' import httpClient from './myClient/httpClient' import A from './src/A' test('a async test', async (t) => { const instance = new A() const stubbedHttpInit = sinon.stub(httpClient, 'init') sinon.stub(fetch).returns(Promise.resolve({payload: 'data'})) //this doesn't work await instance.init() t.true(stubbedHttpInit.init.calledWith('data')) }) ``` My idea it's check if the httpClient's init method has been called using the payload obtained in a fetch request. My question is: How I can mock the fetch dependency for stub the returned value when i test the A's init method?