TypeError:無法讀取 null 的屬性「類型」 - 使用非同步函數測試 vue 元件
<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)
在 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>