Skip to content

Commit 0cc6f06

Browse files
committed
Added example of mocking and spying on constructor mocks
1 parent 2d09956 commit 0cc6f06

File tree

6 files changed

+48
-11
lines changed

6 files changed

+48
-11
lines changed

jest.config.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
module.exports = {
2+
preset: 'ts-jest',
3+
testEnvironment: 'node',
4+
};

package-lock.json

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
"sequelize": "^5.8.7",
2525
"sequelize-typescript": "^1.0.0-alpha.9",
2626
"ts-jest": "^24.0.2",
27-
"ts-node": "^8.0.3"
27+
"ts-node": "^8.0.3",
28+
"typescript": "^3.3.4000"
2829
}
2930
}

src/services/cat-service.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import Cat from "../models/cat.model";
2+
3+
export class CatService{
4+
public createANewCatByConstructor(name: string, age: number){
5+
const cat = new Cat({
6+
name: name,
7+
age: age
8+
})
9+
}
10+
}

test/cat.test.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import Cat from "../src/models/cat.model";
2+
import { CatService } from "../src/services/cat-service";
3+
4+
// The jest.mock method mocks the whole cat model.
5+
// You will always need to mock the whole model, otherwise you get errors on the initialization of the model.
6+
jest.mock("../src/models/cat.model");
7+
8+
beforeEach(() => {
9+
jest.resetAllMocks();
10+
});
11+
12+
// This test shows how the constructor can be mocked, and how to spy on passed parameters.
13+
describe("given a new instance of the cat model", () => {
14+
it("sets garfield as the name of the cat", () => {
15+
new CatService().createANewCatByConstructor("garfield", 12);
16+
expect(Cat).toBeCalledWith(expect.objectContaining({
17+
name: "garfield",
18+
}));
19+
});
20+
21+
it("sets 12 as the age of the cat", () => {
22+
new CatService().createANewCatByConstructor("garfield", 12);
23+
expect(Cat).toBeCalledWith(expect.objectContaining({
24+
age: 12,
25+
}));
26+
});
27+
});

test/mock-constructor.test.ts

Lines changed: 0 additions & 10 deletions
This file was deleted.

0 commit comments

Comments
 (0)