Javascript 模拟函数时的玩笑范围
我有一个测试,我试图在两种不同的情况下模拟一个组件。当我使用Javascript 模拟函数时的玩笑范围,javascript,reactjs,jestjs,Javascript,Reactjs,Jestjs,我有一个测试,我试图在两种不同的情况下模拟一个组件。当我使用jest.fn时。看起来第一个测试只是从第二个测试中获取值 describe('tests', () => { let sampleArray = new Array() Array.prototype.test = function() { return this.innerArray() } describe('empty', () => { sampleArray.innerArray
jest.fn
时。看起来第一个测试只是从第二个测试中获取值
describe('tests', () => {
let sampleArray = new Array()
Array.prototype.test = function() {
return this.innerArray()
}
describe('empty', () => {
sampleArray.innerArray = jest.fn(() => [])
it('testArray is empty', () => {
expect(sampleArray.test().length).toEqual(0)
})
})
describe('not empty', () => {
sampleArray.innerArray = jest.fn(() => ['test'])
it('testArray is not empty', () => {
console.log(sampleArray.innerArray())
expect(sampleArray.test().length).toEqual(1)
})
})
})
当我console.log
时,我从innerArray获得了我期望的数组,但它看起来好像没有使用它
FAIL test/sample.test.js
tests
empty
✕ testArray is empty (8ms)
not empty
✓ testArray is not empty (4ms)
● tests › empty › testArray is empty
expect(received).toEqual(expected)
Expected value to equal:
0
Received:
1
编辑:如果我把它放在it
范围内,它就会工作。但是为什么我不能在description
范围内完成呢
describe('tests', () => {
let sampleArray = new Array()
Array.prototype.test = function() {
return this.innerArray()
}
describe('empty', () => {
it('testArray is empty', () => {
sampleArray.innerArray = jest.fn(() => [])
console.log(sampleArray.innerArray())
expect(sampleArray.test().length).toEqual(0)
})
})
describe('not empty', () => {
it('testArray is not empty', () => {
sampleArray.innerArray = jest.fn(() => ['test'])
expect(sampleArray.test().length).toEqual(1)
})
})//works
除非您特别希望在所有测试中共享阵列,否则应按如下方式设置阵列:
Array.prototype.test = function() {
return this.innerArray()
}
describe('tests', () => {
let sampleArray
beforeEach(() =>
sampleArray = new Array()
})
// tests...
});
在第一段代码的第一行,您的意思是
const-sampleArray=new-Array()
?@LorenzoMarcon如果没有参数,添加括号并不重要。@Andrew看起来It
函数是异步的。因此,在运行sampleArray.innerArray=jest.fn(()=>[])
之后,它不会运行相应的it
回调,而是运行sampleArray.innerArray=jest.fn(()=>['test'])
,这会导致测试用例失败。@Prakashsharma洞察得很好。但是说到这里,我如何修复它,使我不必在每个测试用例中重复相同的5行代码!非常感谢。我也非常确定您可以使用[]
而不是simpleArray
。在这种情况下,这是正确的。但是我想对我的实际测试进行最接近的复制,这些测试是函数