Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a range of numbers with Jest?

I have:

const BOARD = {
  size: {
    columns: 5,
    rows: 5,
  },
}

and a Redux action creator that generates a position within the board's size:

const generateInitialPlayerPosition = (
  { 
    x = random(0, BOARD_SIZE.size.rows - 1), 
    y = random(0, BOARD_SIZE.size.columns - 1) 
  } = {}) => ({
  type: GENERATE_INITIAL_PLAYER_POSITION,
  payload: { x, y },
  }
)

I need to test that generateInitialPlayerPosition won't return any x or y greater than 4 in this case

like image 597
Julian Betancourt Avatar asked Jun 23 '17 04:06

Julian Betancourt


People also ask

How do I run a specific test in Jest?

So to run a single test, there are two approaches: Option 1: If your test name is unique, you can enter t while in watch mode and enter the name of the test you'd like to run. Option 2: Hit p while in watch mode to enter a regex for the filename you'd like to run.

What are matchers in Jest?

Jest uses "matchers" to let you test values in different ways. This document will introduce some commonly used matchers. For the full list, see the expect API doc.

Is Jest enough for testing?

Jest is a JavaScript test runner that lets you access the DOM via jsdom . While jsdom is only an approximation of how the browser works, it is often good enough for testing React components.

What is deep equality in Jest?

This is a deep-equality function that will return true if two objects have the same values (recursively).


2 Answers

Using methods .toBeGreaterThanOrEqual and .toBeLessThan:

const value = ...
expect(value).toBeGreaterThanOrEqual(lower_inclusive);
expect(value).toBeLessThan(upper_exclusive);
like image 143
diralik Avatar answered Sep 19 '22 07:09

diralik


If they are decimal numbers you can use .toBeCloseTo

test('adding works sanely with decimals', () => {
  expect(0.2 + 0.1).toBeCloseTo(0.3);
});
like image 30
Adrian Avatar answered Sep 22 '22 07:09

Adrian