Skip to content

Commit

Permalink
fix: Allow skipping useExisting. (#1070)
Browse files Browse the repository at this point in the history
Fixes #1066
  • Loading branch information
stephenh committed May 3, 2024
1 parent ffa6efa commit 7085178
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/orm/src/newTestInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { assertNever, maybeRequireTemporal } from "./utils";
export type FactoryOpts<T extends Entity> = DeepPartialOpts<T> & {
use?: Entity | Entity[];
useFactoryDefaults?: boolean | "none";
useExistingCheck?: boolean;
};

// Chosen b/c it's a monday https://www.timeanddate.com/calendar/monthly.html?year=2018&month=1&country=1
Expand Down Expand Up @@ -168,7 +169,7 @@ export function newTestInstance<T extends Entity>(

const createOpts = Object.fromEntries(initialOpts);

if (factoryOpts.useExisting) {
if (factoryOpts.useExisting && testOpts.useExistingCheck !== false) {
const existing = em.entities
.filter((e) => e instanceof meta.cstr)
.find((e) => factoryOpts.useExisting!(createOpts as OptsOf<T>, e as DeepNew<T>));
Expand Down
16 changes: 16 additions & 0 deletions packages/tests/integration/src/EntityManager.factories.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,22 @@ describe("EntityManager.factories", () => {
expect(a2).toMatchEntity(a1);
});

it("can skip creating a singleton", async () => {
const em = newEntityManager();
// Given we have an existing author
const a1 = newTestInstance(em, Author, {}, {});
// And a factory wants to dedup authors on firstName
const a2 = newTestInstance(
em,
Author,
// But the test wants to skip it
{ useExistingCheck: false },
{ useExisting: (opts, existing) => opts.firstName === existing.firstName },
);
// Then we got back a new author
expect(a2).not.toMatchEntity(a1);
});

it("can create and leave required fields unset with noValue", async () => {
const em = newEntityManager();
// Given we want to make a Book
Expand Down

0 comments on commit 7085178

Please sign in to comment.