Julian Betancourt
Julian Betancourt

Reputation: 357

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

Upvotes: 20

Views: 19478

Answers (3)

sun sreng
sun sreng

Reputation: 715

here is my test:

it("should return a random integer between default range of (0,100)", () => {
  const result = getRandomInt();
  expect(result).toBeGreaterThanOrEqual(0);
  expect(result).toBeLessThanOrEqual(100);
});

Upvotes: 1

Adrian
Adrian

Reputation: 9600

If they are decimal numbers you can use .toBeCloseTo

test('adding works sanely with decimals', () => {
  expect(0.2 + 0.1).toBeCloseTo(0.3);
});

Upvotes: 5

diralik
diralik

Reputation: 7196

Using methods .toBeGreaterThanOrEqual and .toBeLessThan:

const value = ...
expect(value).toBeGreaterThanOrEqual(lower_inclusive);
expect(value).toBeLessThan(upper_exclusive);

Upvotes: 41

Related Questions