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

feat: add expect.closeTo() API #2827

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 58 additions & 1 deletion packages/expect/src/jest-asymmetric-matchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { GLOBAL_EXPECT } from './constants'
import { getState } from './state'
import { diff, getMatcherUtils, stringify } from './jest-matcher-utils'

import { equals, isA, iterableEquality, subsetEquality } from './jest-utils'
import { equals, isA, iterableEquality, pluralize, subsetEquality } from './jest-utils'

export interface AsymmetricMatcherInterface {
asymmetricMatch(other: unknown): boolean
Expand Down Expand Up @@ -266,6 +266,56 @@ export class StringMatching extends AsymmetricMatcher<RegExp> {
}
}

class CloseTo extends AsymmetricMatcher<number> {
private readonly precision: number

constructor(sample: number, precision = 2, inverse = false) {
if (!isA('Number', sample))
throw new Error('Expected is not a Number')

if (!isA('Number', precision))
throw new Error('Precision is not a Number')

super(sample)
this.inverse = inverse
this.precision = precision
}

asymmetricMatch(other: number) {
if (!isA('Number', other))
return false

let result = false
if (other === Infinity && this.sample === Infinity) {
result = true // Infinity - Infinity is NaN
}
else if (other === -Infinity && this.sample === -Infinity) {
result = true // -Infinity - -Infinity is NaN
}
else {
result
= Math.abs(this.sample - other) < 10 ** -this.precision / 2
}
return this.inverse ? !result : result
}

toString() {
return `Number${this.inverse ? 'Not' : ''}CloseTo`
}

override getExpectedType() {
return 'number'
}

override toAsymmetricMatcher(): string {
return [
this.toString(),
this.sample,
`(${pluralize('digit', this.precision)})`,
].join(' ')
}
}

export const JestAsymmetricMatchers: ChaiPlugin = (chai, utils) => {
utils.addMethod(
chai.expect,
Expand Down Expand Up @@ -303,11 +353,18 @@ export const JestAsymmetricMatchers: ChaiPlugin = (chai, utils) => {
(expected: any) => new StringMatching(expected),
)

utils.addMethod(
chai.expect,
'closeTo',
(expected: any, precision?: number) => new CloseTo(expected, precision),
)

// defineProperty does not work
;(chai.expect as any).not = {
stringContaining: (expected: string) => new StringContaining(expected, true),
objectContaining: (expected: any) => new ObjectContaining(expected, true),
arrayContaining: <T = unknown>(expected: Array<T>) => new ArrayContaining<T>(expected, true),
stringMatching: (expected: string | RegExp) => new StringMatching(expected, true),
closeTo: (expected: any, precision?: number) => new CloseTo(expected, precision, true),
}
}
16 changes: 10 additions & 6 deletions packages/expect/src/jest-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -446,12 +446,12 @@ export const subsetEquality = (
seenReferences.set(subset[key], true)
}
const result
= object != null
&& hasPropertyInObject(object, key)
&& equals(object[key], subset[key], [
iterableEquality,
subsetEqualityWithContext(seenReferences),
])
= object != null
&& hasPropertyInObject(object, key)
&& equals(object[key], subset[key], [
iterableEquality,
subsetEqualityWithContext(seenReferences),
])
// The main goal of using seenReference is to avoid circular node on tree.
// It will only happen within a parent and its child, not a node and nodes next to it (same level)
// We should keep the reference for a parent and its child only
Expand Down Expand Up @@ -522,3 +522,7 @@ export const generateToBeMessage = (

return toBeMessage
}

export const pluralize = (word: string, count: number): string => {
return `${count} ${word}${count === 1 ? '' : 's'}`
}
1 change: 1 addition & 0 deletions packages/vitest/src/types/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ declare global {
objectContaining(expected: any): any
arrayContaining<T = unknown>(expected: Array<T>): any
stringMatching(expected: string | RegExp): any
closeTo(expected: any, precision?: number): any
}

interface JestAssertion<T = any> extends jest.Matchers<void, T> {
Expand Down
8 changes: 7 additions & 1 deletion test/core/test/jest-expect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,13 @@ 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),
bartoszgolebiowski marked this conversation as resolved.
Show resolved Hide resolved
})
// TODO: support set
// expect(new Set(['bar'])).not.toEqual(new Set([expect.stringContaining('zoo')]))
})
Expand Down