Vue.js 在单元测试中使用模拟获取响应时,Vue组件无法呈现
我想测试BootstrapVue表是否基于API提供的数据正确呈现。作为其中的一部分,我模拟了Vue.js 在单元测试中使用模拟获取响应时,Vue组件无法呈现,vue.js,jestjs,mocking,fetch-api,bootstrap-vue,Vue.js,Jestjs,Mocking,Fetch Api,Bootstrap Vue,我想测试BootstrapVue表是否基于API提供的数据正确呈现。作为其中的一部分,我模拟了fetch函数。当我使用loadItems()方法静态地提供数据时,它工作得很好-渲染了3行。但是当我改为使用API调用方法getData()时,行不会被呈现 模拟fetch似乎在成功记录API响应时起作用,但它似乎无法进入Vue组件的数据选项 要测试的Vue组件: // MenuTable.vue <template> <div> <b-table class
fetch
函数。当我使用loadItems()
方法静态地提供数据时,它工作得很好-渲染了3行。但是当我改为使用API调用方法getData()
时,行不会被呈现
模拟fetch
似乎在成功记录API响应时起作用,但它似乎无法进入Vue组件的数据选项
要测试的Vue组件:
// MenuTable.vue
<template>
<div>
<b-table class="table"
:items="items" :fields="fields">
</b-table>
</div>
</template>
<script>
export default {
methods: {
getData() {
fetch('https://www.myexampleapi.com/menu', {
method: 'GET',
mode: 'cors',
})
.then((response) => response.json())
.then((data) => {
console.log(data);
this.items = data;
})
.catch((error) => {
this.error = error.message;
console.log(error);
});
},
loadItems() {
return [
{ cost: 10, food: 'Spaghetti' },
{ cost: 20, food: 'Pizza' },
{ cost: 30, food: 'Hamburger' },
];
},
},
created() {
this.items = this.loadItems(); // load items statically
this.getData(); // load items from API
},
data() {
return {
fields: ['food', 'cost'],
items: [],
};
},
};
</script>
// MenuTable.spec.js
import { mount, createLocalVue } from '@vue/test-utils';
import MenuTable from '@/components/MenuTable.vue';
// eslint-disable-next-line no-unused-vars
import { BootstrapVue, BButton, BTable, BRow } from 'bootstrap-vue';
// create an extended `Vue` constructor
const localVue = createLocalVue();
// install plugins as normal
localVue.use(BootstrapVue);
describe('Table.vue Buttons Test', () => {
let wrapper = null;
// SETUP - run before to each unit test
beforeEach(() => {
global.fetch = jest.fn(() => Promise.resolve({
json: () => Promise.resolve([
{ cost: 10, food: 'Spaghetti' },
{ cost: 20, food: 'Pizza' },
{ cost: 30, food: 'Hamburger' },
]),
}));
// render the component
wrapper = mount(MinimalTable, {
localVue,
});
});
// TEARDOWN - run after to each unit test
afterEach(() => {
jest.resetModules();
jest.clearAllMocks();
jest.restoreAllMocks();
wrapper.destroy();
});
it('renders three rows', () => {
const tableComponent = wrapper.findAll('tbody > tr');
console.log(tableComponent.length);
expect(tableComponent.length).toEqual(3);
});
});
我已经通过使用mount
来确保这不是一个问题,我想我已经通过使用承诺来确保测试等待API响应的响应
为什么可以记录API响应数据,但不将其分配给
项
数据变量?看起来您希望Jest自动等待承诺,但实际上您必须明确地这样做。当fetch
的Promise
解析时,您可以通过等待setTimeout()
来等待下一个宏勾选,无需指定延迟:
it('呈现三行',异步()=>{
//当'fetch'承诺解析时等待宏勾选
等待新承诺(r=>setTimeout(r))
const tableComponent=wrapper.findAll('tbody>tr');
console.log(tableComponent.length);
期望值(表分量.长度).toEqual(3);
})