Home > front end >  How to test an internal function
How to test an internal function

Time:01-13

I'm trying to create a unit test to cover an internal function

fileA.js

module.exports.functionA = () {
  
  const functionB = () {
    // do something
  }

  functionB()
}

test.js

const { functionA } = require('fileA')

...

it('runs functionB', () => {
  functionA()
  expect(...).toHaveBeenCalled()
}

How do I access it?

CodePudding user response:

There are two possibilities here (your situation looks like the first one, but is also clearly simplified for the purposes of the question).

Either:

  • functionB is entirely private to functionA, part of its implementation, which means you can't access it to test it (directly). Instead, test functionA, which presumably uses functionB as part of the work it does (otherwise, there's no point in an entirely private function in functionA).

    or

  • functionA exposes functionB in some way (for instance, as a return value, or as a method on a returned object, or by setting it on an object that's passed in, etc.), in which case you can get it in whatever way functionA provides and then test it.

(Again, I think yours is the first case.)

  •  Tags:  
  • Related