I can't properly mock getConnection
method from pool
in mysql2
lib. My setup is next:
"ts-mockito": "^2.6.1"
"typescript": "^4.8.4"
"mocha": "^10.1.0",
"mysql2": "^2.3.3",
Test:
import { Pool, PoolConnection } from "mysql2/promise";
import { mock, instance, verify, when} from "ts-mockito";
import Service from './'
describe("Conn test", function() {
const connPool = mock<Pool>();
const connection = mock<PoolConnection>();
when(connPool.getConnection()).thenResolve(instance(connection));
const service = new Service(
instance(connPool)
)
it("Should save info", async function() {
const res = await service.saveInfo(command);
expect(res).to.not.throw;
});
}
Code:
class Service {
constructor(readonly pool: Pool) {}
async saveInfo(txt: string) {
const conn = await this.pool.getConnection();
...
}
}
Test halts on line await this.pool.getConnection()
and timeouts after 2 seconds and outputs error:
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
Increasing timeout did not help.
It seems
ts-mockito
does not work well with JS promise. But there is a workaround, reference: https://github.com/NagRock/ts-mockito/issues/191#issuecomment-708743761index.ts
:index.test.ts
:Test result:
package versions: