网站搜索

jest.mock 在 Javascript 测试和 Typescript 模块中不起作用


我模拟的 utilFunction 没有被使用,并且在工厂函数中添加日志显示它从未被调用。我已经尝试过搜索关于 jest.mock 对相对路径不起作用以及 jest.mock 在 Typescript 中未被调用的问题,想着这可能与 JS 测试和 TS 源代码的混合,或者源代码和测试代码中使用的不同模块路径有关。

正在测试的代码:

// src/foo/fooModule.ts
import { utilFunction } from '../util'

export const foo = () => {
  return utilFunction()
}

测试代码:

// test/fooModule.test.js
const { foo } = require('../src/foo/fooModule')

jest.mock('../src/util', () => {
  return { utilFunction: () => 'mocked' };
});

describe('fooModule tests', () => ...)

答案#1

jest.mock 调用需要移动到导入语句的 上方:

// test/fooModule.test.js
jest.mock('../src/util', () => {
  return { utilFunction: () => 'mocked' };
});

const { foo } = require('../src/foo/fooModule')


describe('fooModule tests', () => ...)

在此之前,我上一次使用 Jest 的经历是在一个项目中,该项目中的测试也是用 TypeScript 编写的,并且使用了 babel-jest。babel-jest 包含 babel-jest-hoist,它会自动将 jest 模拟提升到任何导入之上,所以我以前不需要担心顺序问题。

相关文章