我得到了错误:
ReferenceError: Cannot access 'myMock' before initialization
我要这么做:
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,
})
}
}
});
正如您所看到的,我的两个变量都尊重“标准”,但没有正确地悬挂。
我漏掉了什么吗?
显然,当我只通过jest.fn()
而不是变量时,它就能工作,但是我不知道以后如何在我的测试中使用这些。
发布于 2021-04-15 19:07:15
当您需要监视const
声明时,接受的答案不会处理,因为它是在模块工厂范围内定义的。
对我来说,模块工厂需要是,而不是--任何最终导入您想要模拟的东西的导入语句。下面是一个使用雀巢和普里斯马库的代码片段。
// 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();
});
)};
发布于 2021-06-21 19:31:04
上面的答案都解决不了我的问题,下面是我的解决方案:
var mockMyMethod: jest.Mock;
jest.mock('some-package', () => ({
myMethod: mockMyMethod
}));
在进口产品之前使用const让我觉得很奇怪。事情是:jest.mock
被吊起来了。为了能够在变量之前使用它,您需要使用var
,因为它也是悬挂的。它不适用于let
和const
,因为它们不起作用。
发布于 2021-05-19 00:49:37
要澄清贾森·利曼托罗的意思,请将const
移到导入模块的位置上:
const mockMethod1 = jest.fn(); // Defined here before import.
const mockMethod2 = jest.fn();
import MyClass from './my_class'; // Imported here.
import * as anotherClass from './another_class';
jest.mock('./my_class', () => {
return {
default: {
staticMethod: jest.fn().mockReturnValue(
{
method1: mockMethod1,
method2: mockMethod2,
})
}
}
});
https://stackoverflow.com/questions/65554910
复制相似问题