每当我尝试使用 Node.js 中的 jest.js 来模拟类中声明的异步函数时。它不是模拟函数,而是进入其实现内部。但同样的事情被其他用户嘲笑为相同的代码。不知道为什么?
我尝试模拟整个文件,然后在测试中使用它,但它仍然不起作用。 以下是我想编写笑话代码的js文件(例如)
索引.js
class MyClass {
constructor() {
// Constructor code here
}
async fetchData() {
try {
// Simulating an asynchronous operation
// like fetching data from an API
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Failed to fetch data');
}
const data = await response.json();
// Some additional logic with the fetched
// data
const processedData = data.map(item =>
item.name.toUpperCase());
return processedData;
} catch (error) {
console.error('Error fetching data:', error.message);
throw error;
}
}
}
module.exports = MyClass;
在此我试图模拟获取数据函数,例如
Myclass.prototype.fetchData =
jest.fn().mockReturnValue(1);
但是,流程不是模拟,而是进入其实际实现内部。 那么如何解决上述问题呢?
您是否尝试过使用
jest.spyOn
来模拟 fetchData
的 MyClass
功能:
describe("MyClass Test", () => {
it("should fetch data from an API", async () => {
const myClass = new MyClass();
const mockFetchData = jest.spyOn(myClass, "fetchData");
mockFetchData.mockResolvedValue({ test: true });
const data = await myClass.fetchData();
expect(mockFetchData).toHaveBeenCalledTimes(1);
expect(data).toEqual({ test: true });
});
});