Created
August 7, 2023 19:54
-
-
Save BlairCurrey/aa5df18a73269250f49687e95563bd5f to your computer and use it in GitHub Desktop.
How to Mock Objection Models
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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