我有一个测试,我试图在两种不同的情况下模拟一个组件。当我使用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
范围内,它就可以工作。但为什么我不能在 describe
范围内执行此操作?
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...
});
关于javascript - 模拟函数时在 Jest 中确定范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46855281/