Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid variable access: jestPrisma #91

Open
xxjjnn opened this issue May 25, 2023 · 2 comments
Open

Invalid variable access: jestPrisma #91

xxjjnn opened this issue May 25, 2023 · 2 comments

Comments

@xxjjnn
Copy link

xxjjnn commented May 25, 2023

In the documentation it says

/* setup-prisma.js */

jest.mock("./src/client", () => {
  return {
    prisma: jestPrisma.client,
  };
});

When running npm test it says:

    ReferenceError: /Users/myname/w/myrepo/setup-prisma.js: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
    Invalid variable access: jestPrisma

jest.config.js looks like:

module.exports = {
  clearMocks: true,
  preset: './jest-preset',
  testEnvironment: "@quramy/jest-prisma/environment",
  testEnvironmentOptions: {
    verboseQuery: true,
  },
  setupFilesAfterEnv: ["./setup-prisma.js"],
}

It seems there is a problem setting up jestPrisma to be accessible from the 'setup.prisma.js' file?

I tried adding const { jestPrisma } = require('@quramy/jest-prisma'); to the top of 'setup.prisma.js' and it still gave the same error.

const { jestPrisma } = require('@quramy/jest-prisma');

jest.mock("./lib/prisma", () => {
  return {
    prisma: jestPrisma.client,
  };
});
@xxjjnn
Copy link
Author

xxjjnn commented May 25, 2023

I changed setup-prisma.js to:

jest.mock("./lib/prisma", () => {
  const { jestPrisma } = require('@quramy/jest-prisma');
  return {
    prisma: jestPrisma.client,
  };
});

new error!
TypeError: Cannot read properties of undefined (reading 'client')

@frontendphil
Copy link

Try this:

const mockJestPrisma = jestPrisma

jest.mock("./src/client", () => ({
  prisma: mockJestPrisma.client,
}))

When you mock a module this call is hoisted which means that locally declared variables might not be available inside the mock. However, when you a variable name starts with mock then jest allows it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants