I'm trying to write a few unit tests for Vue and instead of setting up a new wrapper each time, I'd like to use beforeEach() to take care of it automatically. When I run the debugger, it fails all of the tests, then runs the beforeEach() function for each of the tests.
This is my .spec.js file.
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);
})
});
The console shows me the test fails:
FAIL: qc-address-view
× sets up a valid address (72ms)
TypeError: Cannot read property 'addrLine1' of undefined
TypeError: Cannot read property 'attributes' of null
It can't read the properties because beforeEach() hasn't set up the object yet.
Then it runs beforeEach() after the test instead of before it:
console.log: beforeEach executed!
When I tried it with three tests, it would fail each test, then console.log would print "beforeEach executed!" three times.
How do I get beforeEach() to run before each test, instead of each one after all?
The answer was to put the id
and address
into an attrs
object, thus:
wrapper = mount(QcAddressView, {
attrs: {
id,
address: {
addrLine1: '111 Testerson Way',
addrLine2: '',
cityName: 'Olympia',
stateCode: 'WA',
zipCode: '98512',
countyName: 'Thurston',
countryName: 'United States of America',
},
}
})