Closed sweatpotato13 closed 9 months ago
Since your test does not operate with database and you mocked Transactional annotation, you probably don't need to initialize transactional context. Try removing first 4 lines in your beforeEach block.
Has anybody figured out how to mock @Transactional()
?
I just add this code and works
jest.mock("typeorm-transactional", () => ({
Transactional: () => () => ({}),
runOnTransactionCommit: () => () => ({}),
runOnTransactionRollback: () => () => ({}),
runOnTransactionComplete: () => () => ({})
}));
@sweatpotato13 thanks for the reply... I tried your suggested code, and I still get the following:
No storage driver defined in your app ... please call initializeTransactionalContext() before application start.
31 |
32 | beforeEach(async () => {
> 33 | const transactionalContext = getTransactionalContext();
| ^
34 | if (!transactionalContext) {
35 | initializeTransactionalContext();
36 | }
@sweatpotato13 and for anyone else in my situation...
UPDATE - Great news! I moved the jest.mock to be outside of the top-level describe
block, just below my import
statements, and added a mock for initializeTransactionalContext
and it worked!
In this example, I have a 'MyController' which has a createAndSave
endpoint with @Transactional()
decorator above it.
import { initializeTransactionalContext } from "typeorm-transactional";
import { Test, TestingModule } from "@nestjs/testing";
import { getRepositoryToken } from "@nestjs/typeorm";
import { MyService } from "./my.service";
import { MyController } from "./my.controller";
import { MyEntity } from "./my.entity";
jest.mock("typeorm-transactional", () => ({
Transactional: () => () => ({}),
runOnTransactionCommit: () => () => ({}),
runOnTransactionRollback: () => () => ({}),
runOnTransactionComplete: () => () => ({}),
initializeTransactionalContext: () => ({}),
}));
describe("MyController", () => {
let myController: MyController;
let myService: MyService;
let app: TestingModule;
const mockMyRepository = jest.fn(() => ({
findOne: jest.fn(),
find: jest.fn(),
// etc.
}));
beforeEach(async () => {
initializeTransactionalContext();
app = await Test.createTestingModule({
controllers: [MyController],
providers: [
MyService,
{
provide: getRepositoryToken(MyEntity),
useValue: mockMyRepository,
},
],
}).compile();
await app.init();
myController = app.get<MyController>(MyController);
myService = app.get<MyService>(MyService);
});
const testEntity: MyEntity = {
id: "1",
name: "my1",
};
beforeEach(() => {
jest.clearAllMocks();
});
afterAll(async () => {
await app.close();
});
describe("createAndSave", () => {
it("should create a My record", async () => {
jest.spyOn(myService, "createAndSave").mockResolvedValueOnce(testEntity);
const result = await myController.createOne(testEntity);
expect(result).toMatchObject(testEntity);
});
});
});
I want to write test code without DB Connect so I tried mocking typeorm
When I tried to write test code below
It comes error like this
Any solution about this?