jest-plugin-set
Declarative JS tests with lazy evaluation for jest.
Getting Started
Install jest-plugin-set
using yarn
:
yarn add --dev jest-plugin-set
Motivation
RSpec took the ruby world by storm with its declarative method of TDD. Since moving to JavaScript, I've wanted a similar way of declaring the setup for my tests. Here's what you would normally do to declare a test:
;
Some notes:
- Because of scoping in javascript, we have to declare our variables outside the
beforeEach
blocks in order to reference them. - Our
beforeEach
blocks contain all of the setup code necessary which in this trivial example is at least 3 lines per test. - We can override variables in nested scopes, but following the chain is non-trivial because the actual variable declaration might be several layers up.
Here's what the same tests look like with using set
from jest-plugin-set
:
;
Even in this trivial example, things are much easier to follow.
- We can declare
firstName
andlastName
as variables that we can then reference in ourbeforeEach
blocks. - We can break up the large
beforeEach
blocks into several distinctset
blocks. - We can easily set defaults in outer scopes (which may or may not be used within a particular test saving performance) and then overriding the values in nested blocks.
set
?
Why In JavaScript, let
is a keyword so the next closest word is...set
(which still keeps the meaning of what we're doing - settings variables (lazily)).
Usage
If you want, you can import set
from jest-plugin-set
at the top of every test:
;
If you want to install set
as a global, you can modify the jest
section of your package.json
to include:
"jest":
Example
Here's an example test that tests set
itself:
;