Jest捕获stdout和stderr输出。是否可以在测试中访问捕获的信息?
问候,尼基尔
答案 0 :(得分:1)
我用错误的方式来做这件事。我没有使用间谍/模拟,而是试图直接拦截stdout / stderr。我使用以下功能解决了该问题。
/* eslint-disable no-undef */
export function spyConsole() {
let spy = {}
beforeEach(() => {
spy.console = jest.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
spy.console.mockClear()
})
afterAll(() => {
spy.console.mockRestore()
})
return spy
}
通过以下方式使用:
import { createLocalVue, mount } from '@vue/test-utils'
import { spyConsole } from '@tst/helpers/test-utils'
import Vuetify from 'vuetify'
import VBtnPlus from '@/components/common/VBtnPlus.vue'
describe('VStatsCard.vue', () => {
let localVue = null
beforeEach(() => {
localVue = createLocalVue()
localVue.use(Vuetify)
})
describe('test prop warnings', () => {
let spy = spyConsole()
it('displays warning messages when both label and icon are not specified', () => {
mount(VBtnPlus, {
localVue: localVue
})
expect(console.error).toHaveBeenCalledTimes(1)
expect(spy.console.mock.calls[0][0]).toContain(
'[Vue warn]: Missing required prop, specify at least one of the following: "label" or "icon"'
)
})
})
})