如何在其他测试块中运行玩笑测试?

Wei*_*Lin 2 testing unit-testing jestjs

例如我有 2 个测试,如何测试一个依赖于另一个测试?有时,我们想要进行一些E2E测试,它可以重现相同的测试步骤。

我现在的想法是使用单独的函数进行测试,但是如果有一种快速的方法可以使用一个语句运行其他测试,那就太好了。

test('test1', () => {
})
test('test2', () => {
  // run test1 here
})
Run Code Online (Sandbox Code Playgroud)

Kap*_*ppa 6

从您对另一个答案的评论中我了解到的是:您想仅为某些特定测试共享测试的一部分。

为此,您可以在块内使用beforeEach和函数。beforeAlldescribe

看我的例子:

describe('some module', () => {
  it('should test something awesome', () => {
    // My test 1
  })

  it('should test something awesome', () => {
    // My test 2
  })

  describe('something specific or tests that are related to each other', () => {
    beforeEach(() => {
      // code that runs for each tests within this describe block
    })

    it('should test something awesome', () => {
      // My test 3
    })

    it('should test something awesome', () => {
      // My test 4
    })
  })
})
Run Code Online (Sandbox Code Playgroud)