When creating unit tests for typeorm, I want to mock my connection to the database so that I can run unit tests without actually ever connecting to the DB (a good thing!)
I see places where people have mocked typeorm's repositories using testdouble (which I am also using), but I am trying to do this with getManager and am having an issue figuring out how to make it work.
Here's an example. I have a class that, in the constructor, creates an EntityManager by using getManager() for a connection called 'test':
export class TestClass {
constructor() {
const test: EntityManager = getManager('test');
}
}
Now I want to test that I can simply create this class. Here's a sample (using mocha, chai, and testdouble):
describe('data transformer tests', () => {
it('can create the test class', () => {
// somehow mock getManager here
const testClass: TestClass = new TestClass();
chai.expect(testClass, 'could not create TestClass').to.not.be.null;
});
});
When I try this, I get this error message from typeorm:
ConnectionNotFoundError: Connection "test" was not found.
Here are some of the things I've tried to mock getManager:
td.func(getManager)
same error as above.
td.when(getManager).thenReturn(td.object('EntityMananger'));
gets the message:
Error: testdouble.js - td.when - No test double invocation call detected for `when()`.
Any ideas what the magic sauce is here for mocking getManager
?
td.when()
? i.e "when called with x then return y"; something along those lines:td.when(getManager(x)).thenReturn(y)
. I think this is what the error message is saying. You need to tell TD what to return for a given function call. – customcommander