【发布时间】:2022-02-05 00:45:50
【问题描述】:
我正在尝试编写一个获取数据的“钩子”(不完全清楚 Vue 中的这个词是什么,而是一个不呈现模板的状态函数)。 Hook 将异步数据解析器作为参数。 hook 本身非常简单,它只是将加载状态添加到返回 promise 的函数中。
import { ref, watch } from "vue";
export function useDataFetcher<T>(
resolver: () => Promise<T>,
) {
const isLoading = ref(false);
const data = ref<T>();
watch(resolver, () => {
isLoading.value = true;
resolver(...parameters)
.then((fetchedData) => {
data.value = fetchedData;
})
.finally(() => {
isLoading.value = false;
});
});
return {
isLoading: isLoading.value,
data,
parameters,
};
}
我正在尝试针对此函数编写测试,以确保 isLoading 方法正确更新:
import { useDataFetcher } from "./useDataFetcher";
test("While the fetcher is loading data, isLoading should be true", async () => {
const promise = new Promise<void>((resolver) =>
setTimeout(() => resolver(), 2000)
);
const { isLoading } = useDataFetcher(() => promise);
expect(isLoading).toBeTruthy();
await promise;
expect(isLoading).toBeFalsy();
});
正如所写,此测试不起作用。我没有在互联网上看到很多关于在 Vue 中测试这些状态函数的信息。 有两个似乎相关的堆栈溢出问题: Is it possible to test a Vue 3 Composition library which uses inject without a wrapping component?
和 How to unit test standalone Vue composition
但这些似乎都不能完全解决我在这里的痒。
在 React 中,您可以使用 @testing-library/react-hooks 库来管理这些测试,这使得它变得非常简单。在我看来,我错过了await Vue.nextTick() 的效果。
那么,最后的问题是:测试这些不呈现模板的 Vue 钩子的最佳方法到底是什么?
【问题讨论】:
标签: vue.js jestjs vuejs3 vue-composition-api