最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jest.mock not working with Javascript test and Typescript module - Stack Overflow

programmeradmin1浏览0评论

My mocked utilFunction isn't being used and adding logging to the factory function shows that it's never called. I've already tried searching for jest.mock not working with relative paths and jest.mock not being called for Typescript thinking that it might be related to the mix of JS tests and TS source code or to the different module paths used in the source vs test code.

Code being tested:

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

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

Test code:

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

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

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

My mocked utilFunction isn't being used and adding logging to the factory function shows that it's never called. I've already tried searching for jest.mock not working with relative paths and jest.mock not being called for Typescript thinking that it might be related to the mix of JS tests and TS source code or to the different module paths used in the source vs test code.

Code being tested:

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

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

Test code:

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

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

describe('fooModule tests', () => ...)
Share Improve this question asked Jun 17, 2022 at 18:06 mowwwalkermowwwalker 17.4k30 gold badges108 silver badges163 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

The jest.mock call needs to be moved above the imports:

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

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


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

My last experience working with Jest prior to this was in a project where the tests were also written in Typescript and babel-jest was used. babel-jest includes babel-jest-hoist which hoists the jest mocks above any imports automatically, so I didn't previously have to worry about the ordering.

发布评论

评论列表(0)

  1. 暂无评论