[英]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.