I'm trying to write some tests for my code. I'm using dependancy injection, and I'm trying to create a faked version of my database to be used when running tests.
I'm using the keyword implements
to define my faked database, however I'm getting typescript errors due to the fact that this faked DB is missing certain properties, however, those properties are private, and never used outside the class
Here's an example:
class Database {
private client: MongoClient;
public async getData(query: string): Promise<{ name: string }> {
return await this.client.db('db').collection('collection').findOne({ name: query });
}
}
class MockDatabase implements Database {
public async getData(query: string): Promise<{ name: string }> {
return {
name: 'Jo'
}
}
}
function makeApp(database: Database) {
console.log(`Here's your app`);
}
const fakeDB = new MockDatabase();
const app = makeApp(fakeDB)
Typescript will error both when declaring MockDatabase
, as well as when using it in the makeApp
function.
Property 'client' is missing in type 'MockDatabase' but required in type 'Database'
How should I approach faking a database or another service like this?