TypeScript 中的 Jest Mock
Rana Hasnain Khan
2022年7月18日

我们将通过示例介绍 Jest Mock
以及如何在 TypeScript 中使用它。
TypeScript 中的 Jest Mock
在开发需要为用户提供完美的商业应用程序时,我们必须确保每个模块按照我们希望的方式工作。为此,我们在 TypeScript 中使用 Jest 模拟。
Jest mock 是一个大型 Web 应用程序的测试框架。通过使用 mock
函数,我们可以监视由某些不同代码间接调用的函数的模块,而不仅仅是测试输出。
如果没有给出实现,则调用 mock
函数时将返回 undefined
。我们可以很容易地使用 jest.mock()
函数,如下所示。
import * as dependency from '../someModule';
jest.mock('../someModule');
jest.mock()
函数会改变依赖的类型,因此我们需要在 TypeScript 中调用 jest.mock()
函数后使用类型转换。我们可以使用 TypeScript 中的 typeof
方法轻松调用类型转换。
让我们来看一个示例,在该示例中,我们将使用自动模拟来测试我们导入到 TypeScript 中的模块,如下所示。
import { testClass } from './testClass';
jest.mock('./testClass');
const mockClass = <jest.Mock<testClass>>testClass;
但是如果我们想手动模拟模块或类,我们也可以轻松做到。让我们看一个示例,我们将在其中手动模拟该类,如下所示。
import testClass from './testClass';
import testClassDependency from './testClassDependency';
const testMockClassDependency = jest.fn<testClassDependency>(() => ({
}));
it('Throw an error', () => {
const testClass1 = new testClass(testMockClassDependency());
});
正如我们从上面的示例中看到的,testMockClassDependency
将创建一个模拟对象实例。我们可以使用类、类型或接口来代替 testClassDependency
。
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn