I have a function that looks roughly like this:
async function getValue(connection: Connection): Promise<number> {
const value = await connection.getValue();
return value < 0 ? value : 0;
}
The important thing to note about this is that Connection
is some huge megaclass and mocking it would take a significant amount of work. I have a function I'm trying to write tests for that calls getValue
two or three nested function calls down, but am having difficulty writing said tests due to Connection
not being available in my unit testing environment. The first way of approaching this I thougt of would be to create a new class, something like ValueGetter
that abstracts away Connection
and then I could just pass in a mock of that into my top level function, like below
class ValueGetter{
connection : Connection;
constructor(connection: Connection){
this.connection = connection;
}
async getValue(): Promise<number> {
const value = await this.connection.getValue();
return value;
}
}
class MockValueGetter{
async getValue(): Promise<number> {
return 0;
}
}
This seems a bit hacky though, so I was wondering if anyone here had a better approach. Thanks a lot!
Connection
is some huge megaclass" I think you know what your real problem is here. I don't particularly like your proposed solution but if you don't have the time to fix the root cause, sometimes you have to do ugly things. – Philip Kendall Jul 05 '23 at 09:58.getValue()
. I didn't add the full code to keep things simpler and focus on the problem at hand – Ahri Jul 05 '23 at 10:53value
out of a complexconnection
then I think you are going to need to mock the, or use a real, connection object. Otherwise any way you organise it you've got a gap in your tests. – Ewan Jul 05 '23 at 11:31