要对 Jest 类方法进行模拟,可以使用 Jest 提供的 jest.fn() 方法来创建一个模拟函数。然后,可以使用 mockReturnValue 方法来指定模拟函数的返回值,以便在测试中验证类方法的行为。
以下是一个示例:
// MyClass.js
class MyClass {
async fetchData() {
// some async code
}
syncMethod() {
// some sync code
}
}
module.exports = MyClass;
// MyClass.test.js
const MyClass = require('./MyClass');
describe('MyClass', () => {
it('should mock async method', async () => {
const myClass = new MyClass();
const fetchDataMock = jest.fn().mockResolvedValue('mocked data');
myClass.fetchData = fetchDataMock;
const result = await myClass.fetchData();
expect(fetchDataMock).toHaveBeenCalled();
expect(result).toBe('mocked data');
});
it('should mock sync method', () => {
const myClass = new MyClass();
const syncMethodMock = jest.fn().mockReturnValue('mocked result');
myClass.syncMethod = syncMethodMock;
const result = myClass.syncMethod();
expect(syncMethodMock).toHaveBeenCalled();
expect(result).toBe('mocked result');
});
});
在上面的示例中,我们首先导入了要测试的 MyClass 类。然后,我们使用 jest.fn() 方法创建了一个模拟函数 fetchDataMock,并使用 mockResolvedValue 方法指定了模拟函数的返回值。
接下来,在测试用例中,我们将 myClass.fetchData 方法指向了模拟函数 fetchDataMock,并在断言中验证了模拟函数被调用,并且返回的结果是我们指定的模拟值。
同样地,我们对同步方法 syncMethod 进行了类似的模拟。
通过使用模拟函数,我们可以在测试中控制类方法的行为,并验证其在不同情况下的表现。
上一篇:按层级提取嵌套列表中的字符串