My MainCreator file is running Sinon tests and I'm having an issue faking some calls when makeIndents is run. It's loading in an external class, HeaderCreator, and calling the function getHeaderCreds from it which is making a real API call.
Is there a way in my beforeEach of MainCreator that I can resolve/fake that external file's function api call?
MainCreator
import { HeaderCreator } from './Headers.js';
export class MainCreator {
///
makeIndents() {
const foo = new HeaderCreator();
foo.getHeaderCreds();
}
}
HeaderCreator
export class HeaderCreator {
getHeaderCreds() {
// config values;
const response = await fetch(`${baseURL}/v1/check`, config);
const { results } = await response.json();
return results;
}
If you test the
makeIndentsmethod of theMainCreatorclass, since thegetHeaderCredsof theHeaderCreatorclass is the direct dependency, you'd better stub it instead of thefetchfunction.I will treat the
makeIndentsmethod as a unit for testing, notmakeIndentsandgetHeaderCreds. This means I will only care about and test the code logic insidemakeIndents. I don't care about the code logic insidegetHeaderCreds. SincegetHeaderCredshas a side effect(network I/O), so I stub it and its return value.According to the above strategy, if you test the
getHeaderCredsmethod, you should stub thefetchfunction and its return value.E.g.
Headers.ts:MainCreator.ts:MainCreator.test.ts:Test result: