有一种情况是,库将代理对象导出为公共API。考虑到库的API无法更改,我无法找到一种方法来使用jest实现代理对象的spyOn。下面是一个示例:
describe("spying on proxied objects with Jest", () => {
it("should pass", () => {
const foo = {
a() {
return 42;
}
};
const p = new Proxy(foo, {
get() {
return () => {
return 53;
};
}
});
const mock = jest.spyOn(foo, "a");
p.a(); // 53
expect(mock).toHaveBeenCalled();
});
});上面的测试用例失败了,因为:
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0有什么想法吗?
发布于 2022-02-21 19:22:14
这是因为foo.a实际上从来没有被调用过,因为代理不调用目标。
这个测试通过了
describe("Foo", () => {
it("should pass", () => {
const foo = {
a() {
return 42;
},
};
const p = new Proxy(foo, {
get(target, prop) {
return () => {
target[prop](); /* <-- Calling target */
return 52;
};
},
});
const mock = jest.spyOn(foo, "a");
const result = p.a(); // 52
expect(mock).toHaveBeenCalled();
});
});https://stackoverflow.com/questions/71211233
复制相似问题