我有一个班级Person.ts
export class Person {
private name: string
constructor(name) {
this.name = name;
}
public getName = () => {
return this.name;
}
}
这个类被实例化,方法getName在我的路由器中被调用
router.post('/user', async (req, res) => {
const person = new Person(req.body.name)
const name = person.getName()
res.json({
name
})
})
现在开玩笑
import request from "supertest"
import { Person } from "../person"
const getNameSpy = jest.spyOn(Person.prototype, "getName")
describe("User route", () => {
it("Should return name", () => {
await request(app).post("/user").send({ name: "john" })
expect(getNameSpy).toHaveBeenCalledTimes(1)
})
})
我收到这个错误
Cannot spy on the getName property because it is not a function; undefined given instead. If you are trying to mock a property, use `jest.replaceProperty(object, 'getName', value)` instead.
我尝试过的其他事情
const mockGetName = jest.fn().mockReturnThis()
jest.mock("../person", () => {
return {
Person: jest.fn().mockImplementation(() => {
return {
getName: mockGetName
}
})
}
})
describe("User route", () => {
it("Should return name", () => {
await request(app).post("/user").send({ name: "john" })
expect(mockGetName).toHaveBeenCalledTimes(1)
})
})
这也行不通。它返回
Expected number of calls: 1
Received number of calls: 0
你会怎么做?