typescript - 测试期间的Vue无限循环
问题描述
以下组件在测试期间以无限重新渲染循环结束,我不知道为什么。它在应用程序中工作得很好,它所做的只是通过事件总线接收一些数据,将其映射到可以在component
标签“is”属性中使用的东西并将其推送到数组中。
<template>
<div id="notification-area">
<div v-for="(component, index) in notificationComponents" :key="index">
<component
:is="component.options"
:notification="component.notification"
/>
</div>
</div>
</template>
<script lang="ts">
import {Component, Inject, Vue} from "vue-property-decorator";
import {Notification, UserErrorNotification, InfoNotification} from "@/Notification";
import InfoNotificationView from "@/components/notifications/InfoNotificationView.vue";
import UserErrorNotificationView from "@/components/notifications/UserErrorNotificationView.vue";
import {ComponentOptions, DefaultComputed, DefaultData, DefaultMethods, PropsDefinition} from "vue/types/options";
type VueOptions = ComponentOptions<
Vue,
DefaultData<Vue>,
DefaultMethods<Vue>,
DefaultComputed,
PropsDefinition<Record<string, {}>>
>
interface NotificationComponent {
options: VueOptions;
notification: Notification;
}
@Component({})
export default class NotificationArea extends Vue {
@Inject('eventBus') private eventBus!: Vue;
private notificationComponents = [] as Array<NotificationComponent>;
private static asNotificationComponent(notification: UserErrorNotification | InfoNotification): NotificationComponent{
if (notification instanceof UserErrorNotification) {
return {options: new UserErrorNotificationView().$options, notification: notification}
}
return {options: new InfoNotificationView().$options, notification: notification}
}
created() {
this.eventBus.$on('notification', (notification: UserErrorNotification | InfoNotification) => {
this.notificationComponents.push(NotificationArea.asNotificationComponent(notification));
})
}
}
</script>
InfoNotificationView
并且UserErrorNotificationView
是 BAlert 的简单包装器。
以下是导致内存不足异常的测试。
describe("NotificationArea.vue", () => {
let wrapper: Wrapper<NotificationArea>;
beforeEach(() => {
wrapper = shallowMount(NotificationArea, {
provide: {
eventBus: new MockEventBus()
},
created() {}
});
});
it("renders the notifications correctly", async () => {
wrapper.setData({
notificationComponents: [successNotificationComponent, warningNotificationComponent]
});
await wrapper.vm.$nextTick() // <-- Here it hangs.
const infoNotification = wrapper.find("infonotificationview-stub");
expect(infoNotification.props('notification')).toBe(successNotificationComponent);
const userErrorNotification = wrapper.find("usererrornotificationview-stub")
expect(userErrorNotification.props("notification")).toBe(warningNotificationComponent);
});
});
解决方案
事实证明,问题在于打印一个非常大的对象,因为successNotificationComponent
它包含一个 vue 组件。
testId
我通过在测试期间将 a 放入通知中并检查它来修复它。