我要测试的功能如下。我们正在使用类似构建器的方法来组装复杂的 URL 结构,以帮助浏览我们的 Web 应用程序。
import { useNavigation } from '../../../blah';
useNavigation().goBack();
我试图检查的完整功能被调用如下
export const useNavigation = (path) => {
const { view } = store.getState();
const withQueryParams = (params = {}) => {
const paramString = addQueryStringParameters(params);
return useNavigation(`${path}${paramString}`);
};
const tlo = (id) => useNavigation(`/${id}/${id}${path}`);
const site = (id) => useNavigation(`/${view.activeTLO.id}/${id}${path}`);
const current = () => useNavigation(`/${view.activeTLO.id}/${view.activeSite.id}${path}`);
const navigate = () => history.push(path);
const goBack = () => history.goBack();
return {
withQueryParams,
tlo,
site,
current,
navigate,
path,
goBack,
};
};
在 Jest 中,我试图模拟内部 goBack 函数,以便我们可以检查它是否在代码中的某个点被调用,但到目前为止我还没有运气。
我正在像这样导入和模拟该函数
import * as navigateTo from '../../../lib/navigateTo';
navigateTo.useNavigation = jest.fn(() => ({
goBack: jest.fn(),
}));
当尝试对 goBack 函数执行期望时,检查它是否被调用,事情变得有点奇怪。
下面的期望确实有效,因为它可以看到navigateTo.useNavigation已被调用,但尽一切努力,我无法检查navigateTo.useNavigation.goBack是否已被调用,因为它始终是未定义的。
it('renders the navigate to the orders page', () => {
const actions = availableOrderActions(settings).find((action) => action.label === 'Supplier Orders');
actions.clickHandler();
expect(navigateTo.useNavigation).toHaveBeenCalled();
});
看起来这就是你模拟这类事情的方式。
import * as navigateTo from '../../../lib/navigateTo';
const goBack = jest.fn();
navigateTo.useNavigation = jest.fn(() => ({
goBack,
}));
it('renders the navigate to orders page', () => {
const actions = availableOrderActions(settings).find((action) => action.label === 'Buyer Orders');
actions.clickHandler();
expect(navigateTo.useNavigation).toHaveBeenCalled();
expect(goBack).toHaveBeenCalled();
});