简体   繁体   中英

testing module functions with jest

I have a module that looks like this:

const config = require('config')
const isActive = config.get('isActive')

const infoMap = new Map()

const set = (key, value) => {
  infoMap.set(key, value)
}

const get = (key) => infoMap.get(key)

module.exports={set, get} 

and a test where I test the stuff:

let get
let set

beforeEach(() => {
  jest.mock('config')
  mockIsActive = require('config').get.mockReturnValueOnce(true)  

  get = require('../cache/mymap').get
  set = require('../cache/mymap').set
})

describe('The map', () => {
  describe('when data is added', () => {
    set('testKey', "testData")

    it('should contains the data', async () => {
      const dataFromMap = get('testKey')
      assert("testData", dataFromMap)
    })
  })
})

It fails when the set is called with:

set is not a function

Strange is that get works without problems.

You must call the set function inside the it function, otherwise it is not yet defined:

describe('when data is added', () => {
    it('should contains the data', async () => {
      set('testKey', "testData")
      const dataFromMap = get('testKey')
      assert("testData", dataFromMap)
    })
  })

beforeEach runs before each it function, not before describe. This is also why get does work in your example - it is inside the it function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM