TypeError:无法读取 null 的属性'类型” - 使用异步函数测试 vue 组件
P粉818306280
P粉818306280 2023-08-28 23:34:29
0
1
551
<p>我正在测试组件 ComponentA.spec.js,但收到 <code>TypeError: Cannot read property 'type' of null</code>。如果我去掉 ComponentA 中 getData() 函数中的 wait 关键字,它就会起作用。我在测试中模拟了 getData api 调用,但它仍然不起作用。</p> <p>这是完整的堆栈 类型错误:C:[隐私]\未知:无法读取 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>这是我正在尝试为其创建测试的组件 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>这是我的 ComponentA.spec.js 文件</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粉818306280
P粉818306280

全部回复(1)
P粉252423906

将异常变量 (e) 添加到 ComponentA 中 getData 函数中的捕获中修复了该问题。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!