Mocha Github问题跟踪器上的这个问题很有意思
https://github.com/mochajs/mocha/issues/3180
此代码按预期工作:
describe('before/after with data-driven tests', () => {
before(() => console.log('before worked'));
beforeEach(() => console.log('beforeEach worked'));
afterEach(() => console.log('afterEach worked'));
after(() => console.log('after worked'));
['foo'].forEach((item) => {
it(`works for item ${item}`, () => {
console.log('item is', item)
})
})
})
但是这段代码很奇怪:
describe('before/after with data-driven tests', () => {
before(() => console.log('before worked'))
beforeEach(() => console.log('beforeEach worked'))
afterEach(() => console.log('afterEach worked'))
after(() => console.log('after worked'))
[ 'foo' ].forEach((item) => {
it(`works for item ${item}`, () => {
console.log('item is', item)
})
})
})
如果用mocha执行第二个示例代码,它会尝试从未定义的变量中读取'foo'。有谁知道为什么?这是错误跟踪:
[ 'foo' ].forEach((item) => {
^
TypeError: Cannot read property 'foo' of undefined
很奇怪!但我相信有一个很好的解释。
答案 0 :(得分:6)
原因是第二个例子中缺少;
:
after(() => console.log('after worked'))
[ 'foo' ].forEach((item) => {
it(`works for item ${item}`, () => {
console.log('item is', item)
})
})
当没有分号时,这意味着"调用函数after
"并从它返回的结果中选择此键。但是在返回undefined
之后,您就会收到错误。