【发布时间】:2021-01-13 14:11:04
【问题描述】:
所以我对使用 react 进行测试还是很陌生。我有一个在组件内部调用的自定义钩子。我正在使用来自react-hook-testing-library 的renderHook 方法。
我需要测试是否调用了自定义钩子内useEffect 内的方法。我似乎无法弄清楚这一点。
在另一种情况下,我需要弄清楚是否没有调用trackPdpGtm。
注意:钩子不返回任何数据。这主要用于发送分析信息。
目前的方法:
使用PdpGtm.js
import { useEffect } from 'react';
import { trackPdpGtm } from 'utils/gtm/pdpGtmUtils';
import _ from 'utils/lodashImports';
export default function useGtmPdp(data = {}) {
console.log('are you getting called?');
const { relatedProducts, results, priceInfo, breadcrumbs } = data;
const relatedProductsLoaded = _.get(relatedProducts, 'relatedProductsLoaded');
useEffect(() => {
if (relatedProductsLoaded) {
trackPdpGtm(data);
}
}, [relatedProductsLoaded, results, priceInfo, breadcrumbs]);
}
我需要测试是否调用了trackPdpGtm。还需要检查它是否没有在另一个测试用例中调用。
gtm.test.js
import { renderHook, cleanup, act } from 'react-hooks-testing-library';
import usePdpGtm from 'utils/hooks/gtmHooks/usePdpGtm';
import useListPageGtm from 'utils/hooks/gtmHooks/useListPageGtm';
import { trackPdpGtm } from 'utils/gtm/pdpGtmUtils';
import { trackListPageGtm } from 'utils/gtm/plpGtmUtils';
import { mount, shallow } from 'enzyme';
import { ProductDescriptionComponent } from 'components/business/ProductDescription/ProductDescriptionComponent';
jest.mock('utils/hooks/gtmHooks/usePdpGtm');
jest.mock('utils/hooks/gtmHooks/useListPageGtm');
jest.mock('utils/gtm/pdpGtmUtils');
jest.mock('utils/gtm/plpGtmUtils');
trackPdpGtm.mockImplementation = jest.fn();
// ALSO TRIED trackPdpGtm.mockImplementation(() => jest.fn());
trackListPageGtm.mockImplementation(() => console.log('adadada'));
describe('analytics helper', () => {
afterEach(cleanup);
it('should fire usePdpGtm Hook', async (done) => {
const pdpData = {
relatedProducts: {
collectionProducts: [],
relatedProductsLoaded: true
},
productInfo: {
variants: [{}],
breadcrumbs: [{}],
serviceWarrantyDetails: {
services: [],
warranties: [{}]
}
},
priceInfo: [{}],
breadcrumbs: [{}]
};
const { result } = renderHook(() => usePdpGtm(pdpData));
//THIS IS FAILING
expect(trackPdpGtm).toHaveBeenCalledTimes(1);
expect(result.current).toBeUndefined();
});
it('should fire usePdpGtm Hook without data', () => {
const { result } = renderHook(() => usePdpGtm(undefined));
// NEED TO TEST IF trackPdpGtm is NOT called. (also failing)
expect(trackPdpGtm).toNotBeCalled();
expect(result.current).toBeUndefined();
});
});
还尝试使用trackGtmPdp.mock.calls.length.toBe(1)。
usePdpGtm 挂钩在 ProductDescriptionComponent 内部调用,并接收一个对象作为其参数。
注意:自定义挂钩在测试期间未运行。我不确定,但在测试运行时不会打印里面的 console.log 语句。
非常感谢任何帮助。
【问题讨论】:
-
谢谢,但这并不包括我想要做的事情。
标签: javascript reactjs jestjs react-testing-library react-hooks-testing-library