let-given
TypeScript icon, indicating that this package has built-in type declarations

0.3.0 • Public • Published

Context variables for testing frameworks

let-given NPM version

Well-typed context variables for testing frameworks with async functions support

Fast example
const { useGiven } = require("let-given");

const { letGiven, it } = useGiven();

describe("User", () => {
  letGiven("user", async ({ userParams }) => {
    return await User.create(userParams);
  }, ["userParams"])

  letGiven("userParams", ({ name, phone, key }) => {
    return {
      name: name,
      phone: phone,
      key: key
    }
  }, ["name", "phone", "key"]);

  letGiven("name", () => "John");
  letGiven("phone", () => "123456789");
  letGiven("key", async () => await (new KeyGenerator()).generate());

  it("successful save", ({ user, key }) => {
    expect(user.isPersisted).toBeTruthy();
    expect(user.name).toEqual("John");
    expect(user.phone).toEqual("123456789");
    expect(user.key).toEqual(key);
  });

  describe("wrong key", () => {
    letGiven("key", () => undefined);

    it("failed save", ({ user }) => {
      expect(user.isPersisted).toBeFalsy();
      expect(user.errors).toEqual("Wrong key");
    });
  });

  describe("with optional field city", () => {
    letGiven("city", () => "London");
    letGiven("userParams", ({ userParams, city }) => {
      userParams.city = city;

      return userParams;
    });

    it("successful save", ({ user }) => {
      expect(user.isPersisted).toBeTruthy();
      expect(user.city).toEqual("London");
    });

    describe("wrong city", () => {
      letGiven("city", () => "New York");

      it("failed save", ({ user }) => {
        expect(user.isPersisted).toBeFalsy();
        expect(user.errors).toEqual("City is not located in UK");
      });
    });
  });
});

Getting started

Installation

npm install let-given --save-dev

Usage

let-given is compatible with all popular testing frameworks(mocha, jasmine and jest). You can also use it with other frameworks

const { useGiven } = require("let-given");

const { letGiven, it } = useGiven();

describe("User", () => {
  letGiven("user", ({ userParams }) => User.create(userParams), ["userParams"])
  letGiven("userParams", ({ name }) => ({ name }), ["name"]);

  letGiven("name", () => "John");

  it("successful save", ({ user, key }) => {
    expect(user.isPersisted).toBeTruthy();
    expect(user.name).toEqual("John");
  });
});

letGiven function

letGiven describes a context variable. It takes 3 parameters: variable name, variable definition function and an array of dependencies of this variable.

letGiven(name: string, func: (given: object) => any, dependencies: string[]);
  • name - The name of the context variable. It will be used as the name of the field and in the dependency array
  • func - A function that defines a variable. The value it will return will be the value of that context variable
  • dependencies - An array of variable names on whose values this variable depends. The values of these dependencies will be passed to the func

Features

Assertation "it" redefine

let-given determines which test framework it works with. And returns the wrapped "it" functions in useGivendepending on the framework

// jasmine
const { letGiven, it, xit, fit } = useGiven();
// jest
const { letGiven, it, fit, xit, test, xtest } = useGiven();
// mocha(it object includes fields only, skip)
const { letGiven, it } = useGiven();
const { only, skip } = it;

Like the original "it", the second argument of wrapped "it" function takes an assertation function. However, in the wrapped version, the given object with all the variables created by letGiven will be passed to this function as the first argument.

letGiven("name", () => "John");
it("successful save", function (given) {
  expect(given.name).toEqual("John");
});

Execute only the last variable definition

let-given will not execute functions for variables that are redefined deeper in the test suites

letGiven("name", async () => {
  // this code will not execute
  const slowNameGenerator = await slowGenerator.generateSlowNameGenerator();
  return await slowNameGenerator.generate();
});
describe("with simple name", () => {
  letGiven("name", () => "John");

  it("successful save", function (given) {
    expect(given.name).toEqual("John");
  });
});

The exception is the use of super variables

Full typescript support

let-given has strong typescript typing

// In a typescript, you must specify a test framework
import useGiven from "let-given/jasmine"; // There are available: "let-given/jasmine", "let-given/mocha", "let-given/jest"

interface Given {
  name: string,
  userParams: object,
  user: User
}

const { letGiven, it } = useGiven<Given>();

describe("User", () => {
  letGiven("user", ({ userParams }) => User.create(userParams), ["userParams"])
  letGiven("userParams", ({ name }) => ({ name }), ["name"]);

  letGiven("name", () => "John");

  it("successful save", ({ user, key }) => {
    expect(user.isPersisted).toBeTruthy();
    expect(user.name).toEqual("John");
  });
});

The type of each context variable is described in the interface, which is passed in the useGiven parameters. If you try to define an undeclared let-given variable, or use an undeclared variable as a dependency, the typescript will throw an error

Asynchronous functions

You can pass an asynchronous function to letGiven. In this case, let-given will wait for the resolution of the promise and in function where this variable is used, the value of the result of this promise will be used. This avoids await async hell in code

letGiven("key", async function ({ userParams }) {
  const secret = await File.load('key.pem');
  const keyGenerator = new KeyGenerator(secret);
  return await keyGenerator.create();
});

it("successful save", ({ key }) => {
  expect(typeof key).toEqual('string');
});

Super variables

letGiven allows you to specify the same variable as a dependency. In this case, the value of the same variable declared above in the test suite will be passed to the function

letGiven("name", () => "John");
describe("with last name", () => {
  letGiven("name", ({ name }) => `${name} Pavlov`, ['name']);

  it("successful save", function ({ name }) {
    expect(name).toEqual("John Pavlov");
  });
});

Custom "it" wrap

If you are using a testing framework other than (mocha, jasmine and jest), then you can use useGivenWithWrapper to wrap any "it" functions

const { letGiven, test, it } = useGivenWithWrapper({
  test: test,
  it: it
});

useGivenWithWrapper will return the wrapped functions in the same fields in which they were passed in the parameters

Alternatives

There are several packages that implement context variables

Some of them have more functionality than let-given. However, they are most often badly typed. And they all don't support asynchronous functions

Benefits of using letGiven

let-given implements context variables similar to let! variables in rspec. Brings all their advantages and takes into account the specifics of javascript and typescript.

These are a few advantages of using the rspec approach for context creation:

Don't repeat yourself

let-given makes it possible to describe only that part of the context that is directly relevant to the test. No need to call fixtures or something at the beginning of each assertation

Test order

Run tests in any order. Context variables exist for only one test. No more dependency on test order

No more global leaks

let-given clears variables after each test. No need to worry about clearing variables between tests

Optimal context build time

Define context variables and their dependencies. let-given take care to prepare the context as quickly as possible

Contributing

You can create issues on github with a description of the issue. You can also create a pull request with fixes. It is important that all tests are passed on the pull request branch.

There are two test folders: dev and dist

  • dev tests are designed to test functionality at the development stage
  • dist tests to test an already compiled distribution.

Run only dev tests

yarn install
yarn test

Run dist test

yarn build # build dist and copy it to node_modules
yarn test:dist # test let-given package from node_modules folder

License

MIT License

Readme

Keywords

none

Package Sidebar

Install

npm i let-given

Weekly Downloads

0

Version

0.3.0

License

MIT

Unpacked Size

38.3 kB

Total Files

46

Last publish

Collaborators

  • ymaril