简体   繁体   English

用 jest 测试模块功能

[英]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被调用时失败:

set is not a function

Strange is that get works without problems.奇怪的是get没有问题。

You must call the set function inside the it function, otherwise it is not yet defined:必须在it函数内部调用set函数,否则还没有定义:

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. beforeEach在每个 it 函数之前运行,而不是在描述之前。 This is also why get does work in your example - it is inside the it function.这也是get在您的示例中起作用的原因 - 它位于it函数内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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