I'm struggling to figure out how to stub a nested Repository in TypeORM. Can anyone assist me in creating a sinon stub for the code snippet below? I attempted to use some code from another Stack Overflow post in my test file, but it's not working as expected. The line of code I need to stub is:
const project = await getManager().getRepository(Project).find({ where: queryParams });
Here is the relevant source code:
project.controller.ts
//getConnection and UpdateResult are not utilized in this function
import {
EntityManager,
getConnection,
getManager,
UpdateResult,
} from "typeorm";
import { Project } from "./project.entity";
import { validate } from "class-validator";
import logger from "../../utils/logger";
export const findOneProject = async (queryParams: {}): Promise<
Project
> => {
try {
const project = await getManager().getRepository(Project).find({
where: queryParams,
});
if (project.length > 1) {
throw new Error("Found more than one project");
}
return project[0];
} catch (e) {
throw new Error(`Unable to find project: ${e.message}`);
}
};
project.test.ts
import sinon from "sinon";
import { findOneProject } from "./project.controller";
import { Project } from "./project.entity";
import { EntityManager, Repository } from "typeorm";
const mockProject = {
ID: "insert-id-here",
name: "name",
};
describe("Testing findOneProject", () => {
it("Should return the same project", () => {
const sandbox = sinon.createSandbox();
// I believe I can stub the repository, but I am unsure how to stub the find() method
sandbox.stub(EntityManager.prototype, "get").returns({
getRepository: sandbox
.stub()
.returns(sinon.createStubInstance(Repository)),
});
const project = await findOneProject(ID: "insert-id-here");
expect(project).toBe(mockProject);
});
});
Appreciate any help on this!
Edit: I have provided additional details in the test file for clarity.