Wednesday, 27 November 2019

Jest - import multiple tests in a describe block, reusing variables defined in beforeEach()

I am familiar with RSpec where it is very easy to reuse test cases by writing shared examples

shared_example_for 'a cute pet' do 
  it 'tests that the pet is a small' { expect(pet.size).to be_lesser_than(10) }
  it 'tests that the pet can smile' { expect(pet.can_smile?).to be }
end

describe 'The Octocat' do
  let(:pet) Octocat.new

  it_behaves_like 'a cute pet'
end
...
describe 'The Doge' do 
  let(:pet) Doge.new

  it_behaves_like 'a cute pet'
end

Is there an equivalent in Jest ? Something that would let me reuse variables set in beforeEach() blocks ? I am trying to find a way using something like the following :

const cutenessTests = function() {
  test('it is small', () => {
    expect(petSetInBefore.length).toBeLesserThan(5)
  })
  test('it can smile', () => {
    expect(petSetInBefore.canSmile).toBe(true)
  })
}

describe('Famous animals', () => {
  let petSetInBefore;

  describe('Octocat', () => {
    beforeEach(() => {
      petSetInBefore = new Octocat();
    })

    cutenessTests.bind(this)()
  })
})

The important here is that I am trying to share multiple test definitions and not just one, otherwise I could have passed the petSetInBefore to the shared function



from Jest - import multiple tests in a describe block, reusing variables defined in beforeEach()

No comments:

Post a Comment