【问题标题】:Execute BeforeEach Hook before Before Hook in Mocha在 Mocha 中的 Before Hook 之前执行 BeforeEach Hook
【发布时间】:2019-10-14 03:57:08
【问题描述】:

我想创建一个在before Hook 之前执行的beforeEach Hook。

基本上我想要以下行为:

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

【问题讨论】:

    标签: javascript node.js mocha.js


    【解决方案1】:

    我不确定这一点(我没有测试过),但从doc 看来,您的根级别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 根级预挂钩。只需将您的根级beforeEach 转为before 即可解决。

    一般规则是before 回调总是出现在beforeEach 回调“之前”(没有双关语),独立于它们定义的级别。

    【讨论】:

    • 谢谢,我确实检查了文档。问题是我需要一个通用的 beforeEach 应该为每个测试执行(创建每个测试所需的通用数据库模式)。每个测试都有一个特定的“之前”来在数据库中设置不同的案例。
    • 您描述了您使用“解决方法”所做的事情,为什么它在您的情况下不正确?还是我错过了什么?
    • 因为 beforeEach2 应该在单个测试之前只执行一次(这个很简单,但可能存在其他更复杂的)。此外,语法也让其他贡献者感到困惑。我认为它会为我的案例存在一个清晰正确的结构
    • 您不必担心会混淆其他贡献者。这是 mocha 开发者选择遵循的逻辑并且您完全坚持它,没有更清晰的解决方案。你自己解决了。
    • 终于找到了这个类似的问题,有更多的细节:stackoverflow.com/questions/32660241/…。似乎真的很有限
    【解决方案2】:

    您可以使用内部包含 beforeEach() 和 describe() 的 describe()。

    类似的东西

    describe ('A blah component', () => 
    {
      beforeEach(() => {
        console.log('beforeEach')
      })
    
       describe(`tests`, () => {
         before(() => {
           console.log('before')
         })
    
         it('test 1, () => {
           console.log('it')
         })
       })
    }
    

    【讨论】:

    • 谢谢,不幸的是我得到了同样的行为:before > beforeEach > it
    • Mocha 有一个隐含的describe 块。这样,您只添加了一个空级别。
    猜你喜欢
    • 1970-01-01
    • 2015-12-16
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多