本文介绍了使用 TypeScript 在 Jest 中模拟依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当测试在不同文件中具有依赖项的模块并将该模块分配为 jest.mock 时,TypeScript 会给出错误,该方法为 mockReturnThisOnce(或依赖项上不存在任何其他 jest.mock 方法),这是因为它之前已键入.

When testing a module that has a dependency in a different file and assigning that module to be a jest.mock, TypeScript gives an error that the method mockReturnThisOnce (or any other jest.mock method) does not exist on the dependency, this is because it is previously typed.

让 TypeScript 从 jest.mock 继承类型的正确方法是什么?

What is the proper way to get TypeScript to inherit the types from jest.mock?

这是一个简单的例子.

依赖

const myDep = (name: string) => name;
export default myDep;

test.ts

import * as dep from '../depenendency';
jest.mock('../dependency');

it('should do what I need', () => {
  //this throws ts error
  // Property mockReturnValueOnce does not exist on type (name: string)....
  dep.default.mockReturnValueOnce('return')
}

我觉得这是一个非常常见的用例,不知道如何正确输入.

I feel like this is a very common use case and not sure how to properly type this.

推荐答案

您可以使用类型转换,您的 test.ts 应该如下所示:

You can use type casting and your test.ts should look like this:

import * as dep from '../dependency';
jest.mock('../dependency');

const mockedDependency = <jest.Mock<typeof dep.default>>dep.default;

it('should do what I need', () => {
  //this throws ts error
  // Property mockReturnValueOnce does not exist on type (name: string)....
  mockedDependency.mockReturnValueOnce('return');
});

TS 转译器不知道 jest.mock('../dependency'); 改变了 dep 的类型,因此你必须使用类型转换.由于导入的 dep 不是类型定义,您必须使用 typeof dep.default 获取其类型.

TS transpiler is not aware that jest.mock('../dependency'); changes type of dep thus you have to use type casting. As imported dep is not a type definition you have to get its type with typeof dep.default.

当导入的元素是一个类时,你就不必使用 typeof 例如:

When imported element is a class then you don't have to use typeof for example:

import { SomeClass } from './SomeClass';

jest.mock('./SomeClass');

const mockedClass = <jest.Mock<SomeClass>>SomeClass;

当您必须模拟某些节点本机模块时,此解决方案也很有用:

This solution is also useful when you have to mock some node native modules:

import { existsSync } from 'fs';

jest.mock('fs');

const mockedExistsSync = <jest.Mock<typeof existsSync>>existsSync;

如果您不想使用 jest 自动模拟而更喜欢创建手动模拟

In case you don't want to use jest automatic mock and prefer create manual one

import TestedClass from './TestedClass';
import TestedClassDependency from './TestedClassDependency';

const testedClassDependencyMock = jest.fn<TestedClassDependency>(() => ({
  // implementation
}));

it('Should throw an error when calling playSomethingCool', () => {
  const testedClass = new TestedClass(testedClassDependencyMock());
});

testedClassDependencyMock() 创建模拟对象实例TestedClassDependency 可以是类或类型或接口

testedClassDependencyMock() creates mocked object instanceTestedClassDependency can be either class or type or interface

这篇关于使用 TypeScript 在 Jest 中模拟依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:24