【发布时间】:2021-12-31 16:05:31
【问题描述】:
我有一个使用 ClassComponents 和 Chart.js(通过 vue-chart-3)的 vue2 项目。我现在有一个简单的组件,它包装了一个 DoughnutChart 来管理数据和内容。
DBOverviewDoughnut.vue
<template>
<div>
<p>test</p>
<DoughnutChart ref="doughnutRef" :chartData="sharesData"></DoughnutChart>
</div>
</template>
<script lang="ts">
import Component from 'vue-class-component';
import Vue from 'vue';
import { DoughnutChart, ExtractComponentData } from 'vue-chart-3';
import { Prop, Ref } from 'vue-property-decorator';
import { ChartData } from 'chart.js';
@Component({ components: { DoughnutChart } })
export default class DBOverviewDoughnut extends Vue {
@Prop()
private sharesData!: ChartData<'doughnut'>;
@Ref()
private readonly doughnutRef!: ExtractComponentData<typeof DoughnutChart>;
created(): void {
this.assignColors();
}
mounted(): void {
if (this.doughnutRef.chartInstance) {
console.log(this.doughnutRef.chartInstance.data);
}
}
assignColors(): void {
this.sharesData.datasets[0].backgroundColor = [
'#77CEFF',
'#0079AF',
'#123E6B',
'#97B0C4',
'#A5C8ED',
];
}
}
</script>
启动程序它会正常工作,我可以访问mounted 挂钩内的chartInstance。
但现在我想对我的组件进行单元测试。我想设置propsData,这将是图表的输入数据。
DBOverviewDoughnut.spec.ts
import DBOverviewDoughnut from '@/components/dashboard/DBOverviewDoughnut.vue';
import { mount, Wrapper } from '@vue/test-utils';
import { Share } from '@/Share';
describe('DBOverviewDoughnut', () => {
let cut: Wrapper<DBOverviewDoughnut>;
it('should render the correct amount of sections', () => {
cut = mount(DBOverviewDoughnut, {
propsData: {
sharesData: {
labels: ['TestShare1', 'TestShare2', 'TestShare3'],
datasets: [{ data: [11, 22, 33] }]
}
}
});
const chart = cut.findComponent({ ref: 'doughnutRef' });
console.log(chart);
});
});
使用shallowMount() 似乎不起作用,因为我只能从日志中得到这个(没有chartInstance 及其在生产代码中的属性):
VueWrapper {
isFunctionalComponent: undefined,
_emitted: [Object: null prototype] {},
_emittedByOrder: [],
selector: { ref: 'doughnutRef' }
}
所以我想也许我必须挂载该组件,因为 DoughnutChart 也是 Chart.js 图表的包装器。但是在使用mount() 时出现以下错误:
console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
[Vue warn]: `createElement()` has been called outside of render function.
console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
[Vue warn]: Error in render: "Error: [vue-composition-api] must call Vue.use(VueCompositionAPI) before using any function."
found in
---> <DoughnutChart>
<DBOverviewDoughnut>
<Root>
我真的不知道我做错了什么。我在main.ts 中注册了VueCompostionAPI:
import Vue from 'vue';
import { Chart, registerables } from 'chart.js';
import App from './App.vue';
import router from './router';
import store from './store';
import VueCompositionAPI from '@vue/composition-api';
Chart.register(...registerables);
Vue.use(VueCompositionAPI);
new Vue({
router,
store,
render: (h) => h(App),
}).$mount('#app');
关注this post 也不能解决问题。
有人知道出了什么问题吗?如果错误与我的测试设置或chart.js或compositionApi的安装有关,我有点困惑。
【问题讨论】:
-
你想做什么测试?
标签: vue.js unit-testing chart.js vue-composition-api