Skip to content

Didericis/test-vars

Repository files navigation

test-vars

NPM Version Tests

Simple utility to lazily evaluate variables in tests (like rspec's let helper)

Motivation

Writing manageable bdd style tests outside of the frameworks supported by bdd-lazy-var. See the documentation of bdd-lazy-var for reasons why to test in this style.

Usage

How to use with node's built-in test runner:

// @ts-check
import assert from 'node:assert'
import { beforeEach, describe, it } from 'node:test'
import { createTestVars } from '../index.js'

const example = (/** @type {string | null} */ msg) => msg

describe('example()', () => {
  // declare "def" and "reset" functions in a top level test block (required)
  // (this will create state specific to this block)
  const { def, setup, subject } = createTestVars()
  const $foo = def('foo', () => /** @type {string | null} */ (null))
  const $bar = def(
    'bar',
    // ensures the type checker always asks us to await $bar
    () => /** @type {Promise<string | null>}*/ (Promise.resolve($foo()))
  )
  const $subject = subject(async () => example(await $bar()))

  beforeEach(() => {
    // reset test variables before every test (required)
    setup()
  })

  describe('when there is a delay getting $bar', () => {
    beforeEach(() => {
      $bar.def(async () => {
        await new Promise((r) => setTimeout(r, 20))
        return $foo()
      })
    })

    describe("and $foo is set to 'foo'", () => {
      // can redefine variables in "beforeEach" blocks
      beforeEach(() => {
        $foo.def(() => 'foo')
      })

      it("returns 'foo'", async () => {
        assert.equal(await $subject(), 'foo')
      })
    })

    describe('and $foo is not set', () => {
      it('returns null', async () => {
        assert.equal(await $subject(), null)
      })
    })
  })
})

About

lazy var util for testing (inspired by bdd-lazy-var)

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors