Home  >  Q&A  >  body text

TypeError: Cannot read property 'type' of null - Testing vue components using async functions

<p>I'm testing component ComponentA.spec.js and I get <code>TypeError: Cannot read property 'type' of null</code>. If I remove the wait keyword in the getData() function in ComponentA, it works. I mocked the getData api call in my test but it still doesn't work. </p> <p>This is the complete stack TypeError: C: [Privacy]\Unknown: Cannot read property 'type' of null </p> <pre class="brush:js;toolbar:false;">at assert (node_modules/@babel/types/lib/asserts/generated/index.js:284:112) at Object.assertIdentifier (node_modules/@babel/types/lib/asserts/generated/index.js:373:3) at new CatchEntry (node_modules/regenerator-transform/lib/leap.js:93:5) at Emitter.Ep.explodeStatement (node_modules/regenerator-transform/lib/emit.js:535:36) at node_modules/regenerator-transform/lib/emit.js:323:12 at Array.forEach (<anonymous>) at Emitter.Ep.explodeStatement (node_modules/regenerator-transform/lib/emit.js:322:22) at Emitter.Ep.explode (node_modules/regenerator-transform/lib/emit.js:280:40) </pre> <p>This is the component I'm trying to create a test for, A</p> <pre class="brush:js;toolbar:false;"><template> <div class="d-flex flex-row"> <component-b /> <component-c /> </div> </template> <script> import ComponentB from './ComponentB'; import ComponentC from './ComponentC'; import { getData } from 'apis'; export default { name: 'component-a', components: { ComponentB, ComponentC, }, async created() { await this.getData(); }, methods: { // This function is the culprit async getData() { try { const response = await getData(); } catch { // } }, }, }; </script> </pre> <p>This is my ComponentA.spec.js file</p> <pre class="brush:js;toolbar:false;">import Vuetify from 'vuetify'; import ComponentA from 'components/ComponentA'; import { createLocalVue, shallowMount, mount } from '@vue/test-utils'; jest.mock('shared/apis', () => { const data = require('../fixedData/data.json'); return { getData: jest.fn().mockResolvedValue(data), }; }); const localVue = createLocalVue(); let vuetify; function createShallowWrapper(options = {}) { return shallowMount(ComponentA, { localVue, vuetify, ...options, }); } beforeEach(() => { vuetify = new Vuetify(); }); describe('ComponentA', () => { describe('component creation', () => { test('testing', () => { const wrapper = createShallowWrapper(); expect(wrapper).toMatchSnapshot(); }); }); }); </pre></p>
P粉818306280P粉818306280417 days ago529

reply all(1)I'll reply

  • P粉252423906

    P粉2524239062023-08-29 19:55:04

    Adding the exception variable (e) to the capture in the getData function in ComponentA fixed the issue.

    reply
    0
  • Cancelreply