• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

1.8K
Views
jest ReferenceError: no se puede acceder a '' antes de la inicialización

Estoy recibiendo el error:

ReferenceError: Cannot access 'myMock' before initialization

Aunque respeté la documentación de jest sobre la elevación: A limitation with the factory parameter is that, since calls to jest.mock() are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory. An exception is made for variables that start with the word 'mock'.

Estoy haciendo esto:

 import MyClass from './my_class'; import * as anotherClass from './another_class'; const mockMethod1 = jest.fn(); const mockMethod2 = jest.fn(); jest.mock('./my_class', () => { return { default: { staticMethod: jest.fn().mockReturnValue( { method1: mockMethod1, method2: mockMethod2, }) } } });

como puede ver, mis dos variables respetan el "estándar" pero no se elevan correctamente.

Me estoy perdiendo de algo ?

Obviamente, funciona cuando solo paso jest.fn() en lugar de mis variables, pero no estoy seguro de cómo poder usarlas en mi prueba más adelante.

about 3 years ago · Santiago Trujillo
3 answers
Answer question

0

Ninguna de las respuestas anteriores resolvió mi problema, así que aquí está mi solución:

 var mockMyMethod: jest.Mock; jest.mock('some-package', () => ({ myMethod: mockMyMethod }));

Algo sobre el uso de const antes de las importaciones me parece extraño. La cosa es: jest.mock se iza. Para poder usar una variable antes, debe usar var , porque también se eleva. No funciona con let y const porque no lo son.

about 3 years ago · Santiago Trujillo Report

0

La respuesta aceptada no se maneja cuando necesita espiar la declaración const , ya que se define dentro del alcance de la fábrica del módulo.

Para mí, la fábrica de módulos debe estar por encima de cualquier declaración de importación que finalmente importe lo que desea simular. Aquí hay un fragmento de código que usa una biblioteca nestjs con prisma .

 // app.e2e.spec.ts import { Test, TestingModule } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import * as request from 'supertest'; import mockPrismaClient from './utils/mockPrismaClient'; // you can assert, spy, etc. on this object in your test suites. // must define this above the `AppModule` import, otherwise the ReferenceError is raised. jest.mock('@prisma/client', () => { return { PrismaClient: jest.fn().mockImplementation(() => mockPrismaClient), }; }); import { AppModule } from './../src/app.module'; // somwhere here, the prisma is imported describe('AppController (e2e)', () => { let app: INestApplication; beforeEach(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleFixture.createNestApplication(); await app.init(); }); )};
about 3 years ago · Santiago Trujillo Report

0

El problema que aborda la documentación es que jest.mock se levanta pero la declaración const no. Esto da como resultado que la función de fábrica se evalúe en el momento en que se importa el módulo simulado y una variable se encuentra en una zona muerta temporal.

Si es necesario acceder a funciones simuladas anidadas, deben exponerse como parte del objeto de exportación:

 jest.mock('./my_class', () => { const mockMethod1 = jest.fn(); const mockMethod2 = jest.fn(); return { __esModule: true, mockMethod1, mockMethod2, default: { ...

Esto también se aplica a los simulacros manuales en __mocks__ donde solo se puede acceder a las variables dentro de un simulacro.

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error