https://github.com/hustcc/jest-random-mock
🎲 Mock Math.random in jest, with deterministic random number.
https://github.com/hustcc/jest-random-mock
Last synced: 3 months ago
JSON representation
🎲 Mock Math.random in jest, with deterministic random number.
- Host: GitHub
- URL: https://github.com/hustcc/jest-random-mock
- Owner: hustcc
- License: mit
- Created: 2024-02-23T09:07:51.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-02-24T06:53:50.000Z (over 1 year ago)
- Last Synced: 2025-01-12T09:19:07.727Z (5 months ago)
- Language: JavaScript
- Size: 4.88 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# jest-random-mock
> Mock `Math.random` when run unit test cases with jest, output deterministic random number.
[](https://github.com/hustcc/jest-random-mock/actions)
[](https://coveralls.io/github/hustcc/jest-random-mock)
[](https://www.npmjs.com/package/jest-random-mock)
[](https://www.npmjs.com/package/jest-random-mock)## Install
This should only be installed as a development dependency (`devDependencies`) as it is only designed for testing.
```bash
$ 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.
```js
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.
```ts
import { createDeterministicRandom } from "jest-random-mock";const random = createDeterministicRandom();
const v1 = random();
const v2 = random();
```## Random distribution

```ts
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@[hustcc](https://github.com/hustcc).