Reputation: 19640
I have a function which uses mysql connection to make a query and i am attempting to unit test this function, to do this i need to mock mysql. However when i use the jest.mock function to mock a mysql connection it returns the following error.
Cannot find module 'MySQLReplica' from 'src/api/leaderboard/ranks/popularity.test.ts'
popularity.test.ts
import { MySQLReplica } from "@services/mysql.service";
import { IEntityLeaderboardQuery } from "./../leaderboard.interface";
import { PopularityRank } from "./popularity";
import { mocked } from "ts-jest/utils";
jest.mock("MySQLReplica");
describe("Leaderboard - Rank - Popularity", () => {
afterAll(() => {
MySQLReplica.end();
});
const mockedMySQLReplica = mocked(MySQLReplica, true);
it("should get popularity scores", async () => {
const query: IEntityLeaderboardQuery = {
top: "10",
entity_types: ["person"],
region: "Europe",
country: "Germany",
end_date: "2021-06-15",
start_date: "2021-06-01",
rank: "popularity",
};
const result = await PopularityRank(query);
console.log(result);
});
});
services/mysql.service.ts
import mysql from "mysql2/promise";
import { Config } from "@config";
export const MySQLReplica = mysql.createPool({
host: Config.db.replica.host,
database: Config.db.replica.database,
user: Config.db.replica.username,
password: Config.db.replica.password,
waitForConnections: true,
connectionLimit: 500,
queueLimit: 0,
});
export const MySQLWrite = mysql.createPool({
host: Config.db.write.host,
database: Config.db.write.database,
user: Config.db.write.username,
password: Config.db.write.password,
waitForConnections: true,
connectionLimit: 100,
queueLimit: 0,
});
export const MySQLPreparedStatement = mysql.format;
Upvotes: 12
Views: 20180
Reputation: 2610
The moduleName
parameter in jest.mock()
is a path.
See the official docs here.
For example:
import moduleName, {foo} from '../moduleName';
jest.mock('../moduleName', () => {
return {
__esModule: true,
default: jest.fn(() => 42),
foo: jest.fn(() => 43),
};
});
moduleName(); // Will return 42
foo(); // Will return 43
So in your case it would be:
import { MySQLReplica } from "@services/mysql.service";
jest.mock("@services/mysql.service");
Upvotes: 12