I am trying to run through some basic tests to make sure my coverage is adequate.
my class
class Foo {
constructor(host) {}
getUserPrivileges() {
const response = this.host.fetch('myurl');
const data = await response.json();
return data.privilege //string
}
getInfo(userPrivilegeType: string) {
const response = this.host.fetch('myurl/${userPrivilegeType}');
const data = await response.json();
return data;
}
mainFunction() {
const userPrivilegeType = await getUserPrivileges(); // return "free" or "paid"
const data = await getInfo(userPrivilegeType); // returns an object or null
let name = "not specified";
if (data) {
name = data.name;
}
return "Finished with " name;
}
}
if I wanted to run a test for mainFunction()
that it returns a value, how can I mock the inside functions but not mock mainFunction
so that it actually triggers it? I want the function coverage to increase but obviously don't want to make real API fetches to a server.
CodePudding user response:
In this case you would mock host
.
const host = makeWhateverHostIs()
jest.spyOn(host, 'fetch').mockImplementation(url => {
if (url === 'myurl') return { some: 'data' }
if (url === 'myurl/admin') return { some: 'other data' }
})
const foo = new Foo(host)