【问题标题】:jest.mock not working with Javascript test and Typescript modulejest.mock 不适用于 Javascript 测试和 Typescript 模块
【发布时间】:2022-06-18 02:06:43
【问题描述】:

我的模拟 utilFunction 没有被使用,并且将日志记录添加到工厂函数表明它从未被调用过。我已经尝试搜索 jest.mock not working with relative paths 并且 jest.mock 没有被 Typescript 调用,认为它可能与 JS 测试和 TS 源代码的混合或源中使用的不同模块路径有关vs 测试代码。

正在测试的代码:

// 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', () => ...)

【问题讨论】:

    标签: javascript typescript jestjs ts-jest


    【解决方案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-jestbabel-jest 包括 babel-jest-hoist,它会自动将开玩笑的模拟提升到任何导入之上,因此我以前不必担心排序问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      相关资源
      最近更新 更多