What’s the Jest equivalent to RSpec lazy evaluated variables (let)?

In this article, we’ll look at what’s the Jest equivalent to RSpec lazy evaluated variables (let).

What’s the Jest equivalent to RSpec lazy evaluated variables (let)?

The Jest equivalent to RSpec lazy evaluated variables (let) is defining a variable that’s shared between different tests.

For instance, we write

beforeEach(() => {
  let input = 'foo';
  beforeEach(() => {
    setupSomething(input);
  });

  describe('when input is bar', () => {
    beforeAll(() => {
      input = 'bar';
    });

    it('does something different', () => {

    });
  });

  describe('when input is baz', () => {
    beforeAll(() => {
      input = 'baz';
    });

    it('does something different', () => {

    });
  });
});

to define the input variable that’s available for all tests.

We assign values to input with different tests and use it in the setupSomething function for setting up each test.

Conclusion

The Jest equivalent to RSpec lazy evaluated variables (let) is defining a variable that’s shared between different tests.