您可以修补标准的describe() 函数,它将透明地添加钩子。
const originalDescribe = global.describe
const describe = (title, callback) => {
originalDescribe(title, () => {
before(() => {
console.log('describe', title)
});
callback();
});
}
describe('Main', ()=> {
describe('Sub', () => {
it('some tests', ()=> {
console.log('it', 1)
})
it('some tests2', ()=> {
console.log('it', 2)
})
})
describe('Sub 2', () => {
it('some tests', ()=> {
console.log('it', 3)
})
})
})
或者另一种(更简单的)方法就是在每个 describe() 块的开头调用你 beforeDescribe() 钩子。
const beforeDescribeHook = () => {
const title = Cypress.mocha.getRunner().suite.title;
console.log('describe', title)
}
describe('Main', ()=> {
before(beforeDescribeHook)
describe('Sub', () => {
before(beforeDescribeHook)
it('some tests', ()=> {
console.log('it', 1)
})
it('some tests2', ()=> {
console.log('it', 2)
})
})
describe('Sub 2', () => {
before(beforeDescribeHook)
it('some tests', ()=> {
console.log('it', 3)
})
})
})