// https://github.com/posva/jest-mock-warn/blob/master/src/index.js
-import { afterEach, beforeEach, expect, SpyInstance, vi } from 'vitest'
+import type { MockInstance } from 'vitest'
+import { afterEach, beforeEach, expect, vi } from 'vitest'
interface CustomMatchers<R = unknown> {
- toHaveBeenWarned(): R
- toHaveBeenWarnedLast(): R
- toHaveBeenWarnedTimes(n: number): R
+ toHaveBeenWarned: () => R
+ toHaveBeenWarnedLast: () => R
+ toHaveBeenWarnedTimes: (n: number) => R
}
declare module 'vitest' {
}
export function mockWarn() {
+ let warn: MockInstance<Parameters<(typeof console)['warn']>, void>
+ const asserted = new Map<string, string | RegExp>()
+
expect.extend({
toHaveBeenWarned(received: string | RegExp) {
asserted.set(received.toString(), received)
const passed = warn.mock.calls.some((args) =>
typeof received === 'string'
- ? args[0].indexOf(received) > -1
+ ? args[0].includes(received)
: received.test(args[0])
)
if (passed) {
const lastCall = warn.mock.calls[warn.mock.calls.length - 1][0]
const passed =
typeof received === 'string'
- ? lastCall.indexOf(received) > -1
+ ? lastCall.includes(received)
: received.test(lastCall)
if (passed) {
return {
warn.mock.calls.forEach((args) => {
const isFound =
typeof received === 'string'
- ? args[0].indexOf(received) > -1
+ ? args[0].includes(received)
: received.test(args[0])
if (isFound) {
found++
},
})
- let warn: SpyInstance
- const asserted = new Map<string, string | RegExp>()
-
beforeEach(() => {
asserted.clear()
warn = vi.spyOn(console, 'warn')
const nonAssertedWarnings = warn.mock.calls
.map((args) => args[0])
.filter((received) => {
- return !assertedArray.some(([key, assertedMsg]) => {
+ return !assertedArray.some(([_key, assertedMsg]) => {
return typeof assertedMsg === 'string'
- ? received.indexOf(assertedMsg) > -1
+ ? received.includes(assertedMsg)
: assertedMsg.test(received)
})
})
})
}
-declare global {
- namespace Vi {
- interface JestAssertion<T = any> {
- toHaveBeenWarned(): void
- toHaveBeenWarnedLast(): void
- toHaveBeenWarnedTimes(n: number): void
- }
- }
+interface CustomMatchers<R = unknown> {
+ toHaveBeenWarned: () => R
+ toHaveBeenWarnedLast: () => R
+ toHaveBeenWarnedTimes: (n: number) => R
+}
+
+declare module 'vitest' {
+ interface Assertion<T = any> extends CustomMatchers<T> {}
+ interface AsymmetricMatchersContaining extends CustomMatchers {}
}