I have a class in which I instantiate an instance of a redis client as a private variable which is set in the constructor but not passed to the constructor. I have two methods I want to unit test and I want to stub the client to throw an error. This is a simple representation of my class.
class MyClass {
#client;
#host;
#port;
#username;
#password;
constructor(options?: MyConfig) {
options = options || {};
this.#host = options.host || `localhost`;
this.#port = options.port || 6389;
this.#username = options.username || `username`;
this.#password = options.password || `password`;
this.#client = createClient({...})
}
async #init() {
try {
await this.#client.connect();
const exists = await this.#client.exists(KEY);
// i need to mock the client to throw an error here
if(!exists) await this.#client.set(KEY, MY_VALUE);
} catch (err) {
throw err;
}
}
async getResult(count?: number): Promise<number> {
...
// i need to mock the client to throw an error here
this.#client.getScriptResult();
}
}
I'm using mocha and chai, and added sinon to try mocking with no success, what is the right way to unit test this case?