如何用Jest测试一个数字范围?

lyfkaqu1  于 2023-04-27  发布在  Jest
关注(0)|答案(3)|浏览(135)

我有:

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

以及一个Redux action creator,它在棋盘大小范围内生成一个位置:

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 },
  }
)

我需要测试在这种情况下generateInitialPlayerPosition不会返回任何大于4的xy

but5z9lq

but5z9lq1#

使用方法.toBeGreaterThanOrEqual.toBeLessThan

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

uqcuzwp82#

如果是十进制数,可以使用.toBeCloseTo

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

brvekthn3#

以下是我的测试:

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

相关问题