Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add jest-random-mock #135

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

hustcc
Copy link
Contributor

@hustcc hustcc commented Mar 8, 2024

jest-random-mock

jest-random-mock Mock Math.random in jest, with deterministic random number.

Build Status
Coverage Status
npm

Install

This should only be installed as a development dependency (devDependencies) as it is only designed for testing.

$ npm i --save-dev jest-random-mock

Usage

Use the only 3 api for test cases.

  • mock(): Mocks the Math.random, with deterministic random function.
  • clear(): Shut down the mock system, use original Math.random.
  • createDeterministicRandom(): Return a deterministic random number generator.

Use it in jest env.

import { mock, clear } from "jest-random-mock";

beforeEach(() => {
  mock();
});

test("your test cases", () => {
  mock();
  const r1 = Math.random();
  clear();

  mock();
  const r2 = Math.random();
  clear();

  // expect r1 should be same with r2.
});

afterEach(() => {
  clear();
});

Use it as a library.

import { createDeterministicRandom } from "jest-random-mock";

const random = createDeterministicRandom();

const v1 = random();
const v2 = random();

Random distribution

image

import { Chart } from "@antv/g2";
import { createDeterministicRandom } from "jest-random-mock";

const random = createDeterministicRandom();

const chart = new Chart({
  container: "container",
  autoFit: true,
  theme: "academy",
});

const flex = chart
  .spaceFlex()
  .attr("direction", "row")
  .attr("ratio", [1, 1, 1]);

const TIMES = [100, 1000, 10000];

TIMES.forEach((time) => {
  const data = new Array(time).fill(0).map(() => ({ v: random() }));
  flex
    .rect()
    .data(data)
    .encode("x", "v")
    .encode("color", "steelblue")
    .transform({ type: "binX", y: "count", thresholds: 10 })
    .style("inset", 0.5)
    .axis("x", { title: false })
    .axis("y", { title: `${time} times Radnom` });
});

chart.render();

License

MIT

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant