Skip to content

Commit

Permalink
test: update test case, types and documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
Dunqing committed Oct 6, 2023
1 parent bbd68c9 commit 4f765b0
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
23 changes: 23 additions & 0 deletions docs/api/expect.md
Original file line number Diff line number Diff line change
Expand Up @@ -1210,6 +1210,29 @@ If the value in the error message is too truncated, you can increase [chaiConfig
})
```

## expect.closeTo

- **Type:** `(expected: any, precision?: number) => any`
- **Version:** Since Vitest 1.0.0

`expect.closeTo` is useful when comparing floating point numbers in object properties or array item. If you need to compare a number, please use `.toBeCloseTo` instead.

The optional `numDigits` argument limits the number of digits to check **after** the decimal point. For the default value `2`, the test criterion is `Math.abs(expected - received) < 0.005 (that is, 10 ** -2 / 2)`.

For example, this test passes with a precision of 5 digits:

```js
test('compare float in object properties', () => {
expect({
title: '0.1 + 0.2',
sum: 0.1 + 0.2,
}).toEqual({
title: '0.1 + 0.2',
sum: expect.closeTo(0.3, 5),
})
})
```

## expect.arrayContaining

- **Type:** `<T>(expected: T[]) => any`
Expand Down
2 changes: 1 addition & 1 deletion packages/expect/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export interface AsymmetricMatchersContaining {
objectContaining<T = any>(expected: T): any
arrayContaining<T = unknown>(expected: Array<T>): any
stringMatching(expected: string | RegExp): any
closeTo(expected: any, precision?: number): any
closeTo(expected: number, precision?: number): any
}

export interface JestAssertion<T = any> extends jest.Matchers<void, T> {
Expand Down
14 changes: 8 additions & 6 deletions test/core/test/jest-expect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,29 +144,31 @@ describe('jest-expect', () => {
expect('Mohammad').toEqual(expect.stringMatching(/Moh/))
expect('Mohammad').not.toEqual(expect.stringMatching(/jack/))
expect({
title: '0.1 + 0.2',
sum: 0.1 + 0.2,
}).toEqual({
title: '0.1 + 0.2',
sum: expect.closeTo(0.3, 5),
})

expect({
title: '0.1 + 0.2',
sum: 0.1 + 0.2,
}).not.toEqual({
title: '0.1 + 0.2',
sum: expect.closeTo(0.4, 5),
})

expect({
title: '0.1 + 0.2',
sum: 0.1 + 0.2,
}).toEqual({
title: '0.1 + 0.2',
sum: expect.not.closeTo(0.4, 5),
})

expect(() => {
expect({
sum: 0.1 + 0.2,
}).toEqual({
sum: expect.closeTo(0.4),
})
}).toThrowErrorMatchingInlineSnapshot(`"expected { sum: 0.30000000000000004 } to deeply equal { sum: CloseTo{ …(4) } }"`)

// TODO: support set
// expect(new Set(['bar'])).not.toEqual(new Set([expect.stringContaining('zoo')]))
})
Expand Down

0 comments on commit 4f765b0

Please sign in to comment.