在 Mocha 中的 Before Hook 之前执行 BeforeEach Hook
Execute BeforeEach Hook before Before Hook in Mocha
我想创建一个 beforeEach
挂钩,它在 before
挂钩之前执行。
基本上我想要以下行为:
beforeEach(() => {
console.log('beforeEach')
})
describe('tests', () => {
before(() => {
console.log('before')
})
it('test 1', () => {
console.log('it')
})
})
我得到:
before
beforeEach
it
但我想要的输出是:
beforeEach
before
it
获得所需行为的正确结构是什么?
解决方法
目前我找到了一个使用两个嵌套 beforeEach 的解决方法:
beforeEach(() => {
console.log('beforeEach1')
})
describe('tests', () => {
beforeEach(() => {
console.log('beforeEach2')
})
it('test 1', () => {
console.log('it')
})
})
哪个输出是:
beforeEach1
beforeEach2
it
您可以使用包含 beforeEach() 和 describe() 的 describe()。
像这样
describe ('A blah component', () =>
{
beforeEach(() => {
console.log('beforeEach')
})
describe(`tests`, () => {
before(() => {
console.log('before')
})
it('test 1, () => {
console.log('it')
})
})
}
我不确定(我没有测试过)但是从 doc 看来,您的 root-level beforeEach
可能并不像您想象的那样。
...
run spec file/s
|
|--------------> per spec file
suite callbacks (e.g., 'describe')
|
'before' root-level pre-hook
|
'before' pre-hook
|
|--------------> per test
'beforeEach' root-level pre-hook
|
'beforeEach' pre-hook
...
从上图中,您可以看到对于每个 describe
,都会调用 before
root-level pre-hook。把你的root-levelbeforeEach
转成before
应该就解决了
一般规则是 before
回调总是来自 "before"(没有双关语意) beforeEach
回调,独立于它们定义的级别。
我想创建一个 beforeEach
挂钩,它在 before
挂钩之前执行。
基本上我想要以下行为:
beforeEach(() => {
console.log('beforeEach')
})
describe('tests', () => {
before(() => {
console.log('before')
})
it('test 1', () => {
console.log('it')
})
})
我得到:
before
beforeEach
it
但我想要的输出是:
beforeEach
before
it
获得所需行为的正确结构是什么?
解决方法
目前我找到了一个使用两个嵌套 beforeEach 的解决方法:
beforeEach(() => {
console.log('beforeEach1')
})
describe('tests', () => {
beforeEach(() => {
console.log('beforeEach2')
})
it('test 1', () => {
console.log('it')
})
})
哪个输出是:
beforeEach1
beforeEach2
it
您可以使用包含 beforeEach() 和 describe() 的 describe()。
像这样
describe ('A blah component', () =>
{
beforeEach(() => {
console.log('beforeEach')
})
describe(`tests`, () => {
before(() => {
console.log('before')
})
it('test 1, () => {
console.log('it')
})
})
}
我不确定(我没有测试过)但是从 doc 看来,您的 root-level beforeEach
可能并不像您想象的那样。
...
run spec file/s
|
|--------------> per spec file
suite callbacks (e.g., 'describe')
|
'before' root-level pre-hook
|
'before' pre-hook
|
|--------------> per test
'beforeEach' root-level pre-hook
|
'beforeEach' pre-hook
...
从上图中,您可以看到对于每个 describe
,都会调用 before
root-level pre-hook。把你的root-levelbeforeEach
转成before
应该就解决了
一般规则是 before
回调总是来自 "before"(没有双关语意) beforeEach
回调,独立于它们定义的级别。