test: improve warning assertions

This commit is contained in:
Evan You 2019-09-03 16:17:26 -04:00
parent c5ec29ff9b
commit 1e4535dc78

View File

@ -11,6 +11,7 @@ declare global {
export function mockWarn() { export function mockWarn() {
expect.extend({ expect.extend({
toHaveBeenWarned(received: string) { toHaveBeenWarned(received: string) {
asserted.add(received)
const passed = warn.mock.calls.some( const passed = warn.mock.calls.some(
args => args[0].indexOf(received) > -1 args => args[0].indexOf(received) > -1
) )
@ -30,6 +31,7 @@ export function mockWarn() {
}, },
toHaveBeenWarnedLast(received: string) { toHaveBeenWarnedLast(received: string) {
asserted.add(received)
const passed = const passed =
warn.mock.calls[warn.mock.calls.length - 1][0].indexOf(received) > -1 warn.mock.calls[warn.mock.calls.length - 1][0].indexOf(received) > -1
if (passed) { if (passed) {
@ -48,6 +50,7 @@ export function mockWarn() {
}, },
toHaveBeenWarnedTimes(received: string, n: number) { toHaveBeenWarnedTimes(received: string, n: number) {
asserted.add(received)
let found = 0 let found = 0
warn.mock.calls.forEach(args => { warn.mock.calls.forEach(args => {
if (args[0].indexOf(received) > -1) { if (args[0].indexOf(received) > -1) {
@ -71,13 +74,29 @@ export function mockWarn() {
}) })
let warn: jest.SpyInstance let warn: jest.SpyInstance
const asserted: Set<string> = new Set()
beforeEach(() => { beforeEach(() => {
asserted.clear()
warn = jest.spyOn(console, 'warn') warn = jest.spyOn(console, 'warn')
warn.mockImplementation(() => {}) warn.mockImplementation(() => {})
}) })
afterEach(() => { afterEach(() => {
const assertedArray = Array.from(asserted)
const nonAssertedWarnings = warn.mock.calls
.map(args => args[0])
.filter(received => {
return !assertedArray.some(assertedMsg => {
return received.indexOf(assertedMsg) > -1
})
})
warn.mockRestore() warn.mockRestore()
if (nonAssertedWarnings.length) {
nonAssertedWarnings.forEach(warning => {
console.warn(warning)
})
throw new Error(`test case threw unexpected warnings.`)
}
}) })
} }