admin管理员组

文章数量:1303353

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.

本文标签: jestmock not working with Javascript test and Typescript moduleStack Overflow