我有一个测试,我试图在两种不同的情况下模拟一个组件。当我使用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
答案 0 :(得分:1)
除非您特别希望在所有测试中共享数组,否则应按如下方式进行设置:
Array.prototype.test = function() {
return this.innerArray()
}
describe('tests', () => {
let sampleArray
beforeEach(() =>
sampleArray = new Array()
})
// tests...
});