Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modules getting picked from cache #489

Closed
ankitkhedekar opened this issue Jun 9, 2022 · 1 comment
Closed

Modules getting picked from cache #489

ankitkhedekar opened this issue Jun 9, 2022 · 1 comment

Comments

@ankitkhedekar
Copy link

ankitkhedekar commented Jun 9, 2022

Description

Test cases are picking the required subject module from the cache. Hence they don't get the mocked instances of functions/modules that have been replaced using td.replace().

Manually deleting the entry from require.cache solves it. And the next require() call correctly picks up the mocked references. Also such issues occur only when the entire test suite is run, running individual tests don't seem to cause such problems

Issue: General question

As per this section in docs, having td.replace() and require() in the beforeEach() block bypasses module cache, but for some reason this doesn't seem to work in my setup

// test.js

// other tests

describe('Testing module A', () => {
  let depModule, subject
  beforeEach(() => {
    depModule = require('path/to/depModule')
    let mockedFn = td.replace(depModule, 'depFn')
    subject = require('path/to/subjectModule') // refers to original depFn
  })
  afterEach(() => {
    td.reset()
  })
 // it blocks
)

To fix this I am currently maunally deleting references from require.cache. Like below:

beforeEach(() => {

  /** hacky workaround */
  delete require.cache[require.resolve('path/to/subjectModule')]


  depModule = require('path/to/depModule')
  let mockedFn = td.replace(depModule, 'depFn')
  subject = require('path/to/subjectModule') // refers to mocked depFn
})

I would like to understand in such cases what is the cause usually? and if any there are better ways to deal with it?

P.S.: Please correct me if this is not the correct channel for queries

@searls
Copy link
Member

searls commented Jun 10, 2022

This is caused because td.replace is meant to be called INSTEAD of calling require on whatever dependency is faked.

That is to say, I would replace this:

depModule = require('path/to/depModule')
let mockedFn = td.replace(depModule, 'depFn')

With:

 depModule = td.replace(depModule, 'depFn')

@searls searls closed this as completed Jun 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants