我正在尝试为 Vue 编写一些单元测试,而不是每次都设置一个新的包装器,我想使用 beforeEach() 来自动处理它。当我运行调试器时,它会失败所有测试,然后为每个测试运行 beforeEach() 函数。
这是我的 .spec.js 文件。
import {
mount,
} from '@vue/test-utils';
import QcAddressView from './address-view.vue';
const id = 'test_address-view';
describe('qc-address-view', () => {
let wrapper = null
beforeEach(() => {
console.log("beforeEach executed!");
wrapper = mount(QcAddressView, {
id,
address: {
addrLine1: '111 Testerson Way',
addrLine2: '',
cityName: 'Olympia',
stateCode: 'WA',
zipCode: '98512',
countyName: 'Thurston',
countryName: 'United States of America',
},
})
})
test('sets up a valid address', () => {
console.log('sets up a valid address');
expect(wrapper.attributes('id')).toBe(id);
})
});
控制台显示测试失败:
FAIL: qc-address-view
× sets up a valid address (72ms)
TypeError: Cannot read property 'addrLine1' of undefined
TypeError: Cannot read property 'attributes' of null
它无法读取属性,因为 beforeEach() 尚未设置对象。
然后它在测试之后而不是之前运行 beforeEach() :
console.log: beforeEach executed!
当我用三个测试尝试它时,每个测试都会失败,然后 console.log 会打印“beforeEach executed!” 三次。
如何让 beforeEach() 在每次测试之前运行,而不是每次测试?