Skip to content

Instantly share code, notes, and snippets.

@BlairCurrey
Created August 7, 2023 19:54
Show Gist options
  • Save BlairCurrey/aa5df18a73269250f49687e95563bd5f to your computer and use it in GitHub Desktop.
Save BlairCurrey/aa5df18a73269250f49687e95563bd5f to your computer and use it in GitHub Desktop.
How to Mock Objection Models
// https://github.com/Vincit/objection.js/issues/1477
import { Model, QueryBuilder } from "objection";
class Person extends Model {
static get tableName() {
return "persons";
}
id!: number;
name!: string;
}
const PersonService = {
findByName: async (name: string) => {
return await Person.query().where({ name }).first();
},
getAll: async () => {
return await Person.query();
},
};
const mockPeople = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
beforeAll(async () => {
jest.spyOn(Person, "query").mockImplementation(() => {
return QueryBuilder.forClass(Person).resolve(mockPeople);
});
});
describe("PersonService", () => {
it("Can find person by name", async () => {
const name = "Alice";
const person = await PersonService.findByName(name);
expect(person?.name).toBe(name);
});
it("Can get all people", async () => {
const people = await PersonService.getAll();
expect(people).toBe(mockPeople);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment