Jestjs 在Jest中访问捕获的stderr输出

Jestjs 在Jest中访问捕获的stderr输出,jestjs,Jestjs,Jest捕获标准输出和标准输出。是否可以在测试中访问此捕获的信息 您好,尼基尔这件事我做得不对。我没有使用spy/mock,而是试图直接拦截stdout/stderr。我用下面的函数解决了这个问题 /* eslint-disable no-undef */ export function spyConsole() { let spy = {} beforeEach(() => { spy.console = jest.spyOn(console, 'error').moc

Jest捕获标准输出和标准输出。是否可以在测试中访问此捕获的信息


您好,尼基尔

这件事我做得不对。我没有使用spy/mock,而是试图直接拦截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"'
      )
    })
  })
})


什么意思?您是在谈论由JS代码或异常/语法错误/生成错误消息启动的
控制台.log
/
控制台.error
输出吗?我使用了错误的方法。请参见下面的答案。因此,您实际上需要在VueJs中测试道具验证。除了mock
console.error
显然也适用于您(但我不太相信——比如在类似的场景中,React有与性能相关的优化——谁知道VueJS是否有类似的功能)。第二件事是您需要在测试中硬编码错误消息。这在未来可能会改变。最后,它很难阅读。怎么办?只需测试
cm.$vm.options..required
cm.$vm.options..validator()
,就可以按照会议上的建议正常工作。我相信测试会更具可读性和更稳定