question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

If Date Object input is specified as DateTime type gte, lte, lt,gt operator in include's where condition doesn't work

See original GitHub issue

I’m sorry if it’s already known, but I can’t input Date JS object as DateTime type fields at where operators using jestPrisma.client in my environment though original prisma client passes tests.

where: {
                  created_at: {
                    gte: {},
                    ~~~
                    lt: {}
                    ~~~~
                  }
},

The photo shows running first test with prisma-jest, and second with original client.

スクリーンショット 2022-12-10 23 17 17

Version Spec

## node
node: v16.15.0

## DB
Postgresql

## packages
"@quramy/jest-prisma": "^1.3.1",
"jest": "^29.3.1",
"ts-jest": "^29.0.3",
"ts-loader": "^8.0.4",

## prisma
prisma                  : 4.7.1
@prisma/client          : 4.7.1
Current platform        : darwin
Query Engine (Node-API) : libquery-engine 272861e07ab64f234d3ffc4094e32bd61775599c (at node_modules/@prisma/engines/libquery_engine-darwin.dylib.node)
Migration Engine        : migration-engine-cli 272861e07ab64f234d3ffc4094e32bd61775599c (at node_modules/@prisma/engines/migration-engine-darwin)
Introspection Engine    : introspection-core 272861e07ab64f234d3ffc4094e32bd61775599c (at node_modules/@prisma/engines/introspection-engine-darwin)
Format Binary           : prisma-fmt 272861e07ab64f234d3ffc4094e32bd61775599c (at node_modules/@prisma/engines/prisma-fmt-darwin)
Format Wasm             : @prisma/prisma-fmt-wasm 4.7.1-1.272861e07ab64f234d3ffc4094e32bd61775599c
Default Engines Hash    : 272861e07ab64f234d3ffc4094e32bd61775599c
Studio                  : 0.477.0

(Addition) ~It doesn’t reproduce it only just to add created_at Datetime @default(now()) to example-prj’ user model.~ I try to find how to reproduce it asap.

I could reproduce it when condition has include: { where: { [$dateFiledName]: { lt: new Date } } }, so on. Both sqlite and postgresql are reproduced so it may have the problem in js layer .

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["clientExtensions"]
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model User {
  id    String @id
  name  String
  posts Post[]
  createdAt DateTime @default(now())
}

model Post {
  id       String @id
  title    String
  author   User   @relation(fields: [authorId], references: [id])
  authorId String
  createdAt DateTime @default(now())
}
/**
 *
 * @jest-environment-options { "verboseQuery": true }
 *
 */
import { PrismaClient } from "@prisma/client";

describe("Should include date type work around", () => {

  /* NG */
  const prisma = jestPrisma.client;
  /* NG */
  //  const prisma = jestPrisma.originalClient;
  /* OK */
  // const prisma = new PrismaClient();

  beforeEach(async () => {
    await prisma.post.create({
      data: {
        id: "post0",
        title: "post",
        author: {
          create: {
            id: "user0",
            name: "quramy",
          },
        },
      },
    });
  });

  test("include api should work using date type condition", async () => {
    const user = await prisma.user.findFirst({
      where: {
        createdAt: {
          lt: new Date(),
          gte: new Date(new Date().getTime() - 1000 * 60 * 60 * 24),
        },
      },
      include: {
        posts: {
          where: {
            createdAt: {
              lt: new Date(),
              gte: new Date(new Date().getTime() - 1000 * 60 * 60 * 24),
            },
          },
        },
      },
    });

    expect(
      (await prisma.post.findFirst({
        where: {
          author: {
            createdAt: {
              lt: new Date(),
              gte: new Date(new Date().getTime() - 1000 * 60 * 60 * 24),
            },
          },
        },
        include: {
          author: {
            include: {
              posts: {
                where: {
                  createdAt: {
                    lt: new Date(),
                    gte: new Date(new Date().getTime() - 1000 * 60 * 60 * 24),
                  },
                },
              },
            },
          },
        },
      }))!.author,
    ).toStrictEqual(user);
  });
});

I confirmed that internal jest-prisma-core originalClient and jest-prisma jestPrisma.originalClient works by force creating and fetch data with overwriting in node_modules folder. In addition, I noticed that validate method in prisma calls with same data, but slightly different though I don’t know why. It may be clues.

Original client

スクリーンショット 2022-12-11 13 37 08

Proxy client(both jestPrisma.client and jestPrisma.originalClient)

スクリーンショット 2022-12-11 13 36 57

I also found invalidChildren’ value exists in node_modules/@prisma/client/runtime/index.js validate method with jest-prisma proxy though manually PrismaClient in jest test case doesn’t.

Issue Analytics

  • State:open
  • Created 9 months ago
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Quramycommented, Dec 12, 2022

Thanks for reply and testing.

So, what’s the way to resolve this you prefer? At least, I think in anyway this library seem to need some patches for testing all prisma api

Hummm, I’m thinking about this. Please give me some time before I answer the question.

1reaction
Quramycommented, Dec 12, 2022

@tkow Thanks for your investigating and sending the PR.

        this.global.Date = Date

I think this problem is caused by https://github.com/facebook/jest/issues/2549 ( It’s famous jest issue, and tooooo long to read 😭 )

And 3rd party jest environments to tackle the issue are published:

e.g. https://www.npmjs.com/package/jest-environment-node-single-context

For now, I don’t know whether jest-prisma should extend the “workaround” environment or not.

But users can weave jest-prisma function to their own environment like this:

import type { Circus } from "@jest/types";
import type { JestEnvironmentConfig, EnvironmentContext } from "@jest/environment";

import { PrismaEnvironmentDelegate } from "@quramy/jest-prisma-core";
import Environment from "jest-environment-node-single-context";

export default class PrismaEnvironment extends Environment {
  private readonly delegate: PrismaEnvironmentDelegate;

  constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {
    super(config, context);
    this.delegate = new PrismaEnvironmentDelegate(config, context);
  }

  async setup() {
    const jestPrisma = await this.delegate.preSetup();
    await super.setup();
    this.global.jestPrisma = jestPrisma;
  }

  handleTestEvent(event: Circus.Event) {
    return this.delegate.handleTestEvent(event);
  }

  async teardown() {
    await Promise.all([super.teardown(), this.delegate.teardown()]);
  }
}
  1. Would you try the above example and confirm to solve your date le / lte / ge / gte problem?
Read more comments on GitHub >

github_iconTop Results From Across the Web

Having problems with query using where on fields of type ...
Currently Prisma doesn't seem to be supporting queries using ISO Date string AND JS Date object. Whenever I use that in a query...
Read more >
Use $gte and &lte mongo operator if date is in string format in ...
I have dob field like {dob:"02-23-2000"} in database. Now I want to perform $gte and &lte on dob field that is in string...
Read more >
Filter date with $lte and $gte not working - MongoDB
I believe the way you have it formatted would: specify the datetime in the client's local timezone and returns the ISODate with the...
Read more >
Functions, operators, and conditionals | BigQuery
This topic is a compilation of functions, operators, and conditional expressions. To learn more about how to call functions, function call rules, ...
Read more >
How to Determine if a Variable is a Date - Mastering JS
The typeof operator returns 'object' for dates, so you can't use typeof to distinguish whether a value is a date. You should use...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found