feat: add optional generic on array containing (#935)

This commit is contained in:
Gabriel Alves 2022-03-13 21:57:32 -03:00 committed by GitHub
parent 8d2aa174d6
commit 6ca857ba28
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 6 deletions

View File

@ -56,7 +56,7 @@ declare global {
interface AsymmetricMatchersContaining {
stringContaining(expected: string): any
objectContaining(expected: any): any
arrayContaining(expected: unknown[]): any
arrayContaining<T = unknown>(expected: Array<T>): any
stringMatching(expected: string | RegExp): any
}

View File

@ -127,12 +127,12 @@ export class ObjectContaining extends AsymmetricMatcher<Record<string, unknown>>
}
}
export class ArrayContaining extends AsymmetricMatcher<Array<unknown>> {
constructor(sample: Array<unknown>, inverse = false) {
export class ArrayContaining<T = unknown> extends AsymmetricMatcher<Array<T>> {
constructor(sample: Array<T>, inverse = false) {
super(sample, inverse)
}
asymmetricMatch(other: Array<unknown>) {
asymmetricMatch(other: Array<T>) {
if (!Array.isArray(this.sample)) {
throw new TypeError(
`You must provide an array to ${this.toString()}, not '${
@ -287,7 +287,7 @@ export const JestAsymmetricMatchers: ChaiPlugin = (chai, utils) => {
utils.addMethod(
chai.expect,
'arrayContaining',
(expected: any) => new ArrayContaining(expected),
<T = any>(expected: Array<T>) => new ArrayContaining<T>(expected),
)
utils.addMethod(
@ -300,7 +300,7 @@ export const JestAsymmetricMatchers: ChaiPlugin = (chai, utils) => {
;(chai.expect as any).not = {
stringContaining: (expected: string) => new StringContaining(expected, true),
objectContaining: (expected: any) => new ObjectContaining(expected, true),
arrayContaining: (expected: unknown[]) => new ArrayContaining(expected, true),
arrayContaining: <T = unknown>(expected: Array<T>) => new ArrayContaining<T>(expected, true),
stringMatching: (expected: string | RegExp) => new StringMatching(expected, true),
}
}

View File

@ -111,6 +111,20 @@ describe('jest-expect', () => {
expect(['Bob', 'Eve']).toEqual(expect.arrayContaining(['Bob']))
expect(['Bob', 'Eve']).not.toEqual(expect.arrayContaining(['Mohammad']))
expect([
{ name: 'Bob' },
{ name: 'Eve' },
]).toEqual(expect.arrayContaining<{ name: string }>([
{ name: 'Bob' },
]))
expect([
{ name: 'Bob' },
{ name: 'Eve' },
]).not.toEqual(expect.arrayContaining<{ name: string }>([
{ name: 'Mohammad' },
]))
expect('Mohammad').toEqual(expect.stringMatching(/Moh/))
expect('Mohammad').not.toEqual(expect.stringMatching(/jack/))