如何针对控制台错误测试 Vue 组件?
How to test a Vue component against console errors?
测试 Vue/Js 的概念对我来说是新的,所以请多多包涵。通常如果有与 Vue 组件相关的错误,我可以在浏览器控制台中看到它们。
例如,如果我有一个 Vue 组件:
<template>
<div>
{{ number }}
</div>
</template>
<script>
export default {}
</script>
我会看到这样的错误:
[Vue warn]: Property or method "number" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
现在,当我想使用测试工具测试特定组件时,我该如何检查这些错误,我想确保加载组件时没有这些错误。
今天我尝试使用 Jset
来测试它,结果是这样的:
import { mount } from '@vue/test-utils'
import Component from '../Components/Example.vue'
test('it renders without errors', () => {
const wrapper = mount(Component)
expect(wrapper.isVueInstance()).toBe(true);
})
但是,这并没有做到,因为它总是 return true
即使 'number' 没有定义。如何检查组件是否已加载且没有控制台错误。
这不是错误而是警告,这就是组件呈现的原因。
正确的测试策略是测试行为,因为框架不引起警告并不意味着单元正常工作。具有完整代码覆盖率的套件不会在没有失败的情况下导致此类警告。
console.error
可以额外侦测调用以加强测试,但在这种情况下,这完全是多余的:
spyOn(console, 'error');
const wrapper = mount(Component);
expect(wrapper.find('div').text()).toContain('123456'); // easier to do with a snapshot
expect(console.error).not.toHaveBeenCalled();
请注意,console
和其他一些内置方法应该小心监视和模拟,因为它们会干扰测试框架的错误报告。
测试 Vue/Js 的概念对我来说是新的,所以请多多包涵。通常如果有与 Vue 组件相关的错误,我可以在浏览器控制台中看到它们。
例如,如果我有一个 Vue 组件:
<template>
<div>
{{ number }}
</div>
</template>
<script>
export default {}
</script>
我会看到这样的错误:
[Vue warn]: Property or method "number" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
现在,当我想使用测试工具测试特定组件时,我该如何检查这些错误,我想确保加载组件时没有这些错误。
今天我尝试使用 Jset
来测试它,结果是这样的:
import { mount } from '@vue/test-utils'
import Component from '../Components/Example.vue'
test('it renders without errors', () => {
const wrapper = mount(Component)
expect(wrapper.isVueInstance()).toBe(true);
})
但是,这并没有做到,因为它总是 return true
即使 'number' 没有定义。如何检查组件是否已加载且没有控制台错误。
这不是错误而是警告,这就是组件呈现的原因。
正确的测试策略是测试行为,因为框架不引起警告并不意味着单元正常工作。具有完整代码覆盖率的套件不会在没有失败的情况下导致此类警告。
console.error
可以额外侦测调用以加强测试,但在这种情况下,这完全是多余的:
spyOn(console, 'error');
const wrapper = mount(Component);
expect(wrapper.find('div').text()).toContain('123456'); // easier to do with a snapshot
expect(console.error).not.toHaveBeenCalled();
请注意,console
和其他一些内置方法应该小心监视和模拟,因为它们会干扰测试框架的错误报告。