我如何用玩笑测试下载 excel 文件?

How can i test downloading excel file with jest?

我不熟悉用 jest 和 enzyme 测试反应组件。我有这个例子

generateExcelFile = () => {
        const {actions, state} = this.props;
        const dateFrom = state.getIn(['config', 'marketingQuestionReport', 'dateFrom']);
        const dateTo = state.getIn(['config', 'marketingQuestionReport', 'dateTo']);

        this.setState({isLoading: true, isLoadingFinished: false});
        fetch(`${env.MARKETING_QUESTION_REPORT}?dateFrom=${dateFrom}&dateTo=${dateTo}`)
            .then((resp) => resp.blob())
            .then((blob) => {
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    window.navigator.msSaveBlob(
                        blob,
                        `Marketing Question Report from ${dateFrom} to ${dateTo}.xlsx`
                    );
                }

                const url = window.URL.createObjectURL(blob);
                const tempLink = document.createElement('a');
                tempLink.style.display = 'none';
                tempLink.href = url;
                tempLink.setAttribute(
                    'download',
                    `Marketing Question Report from ${dateFrom} to ${dateTo}.xlsx`
                );

                if (typeof tempLink.download === 'undefined') {
                    tempLink.setAttribute('target', '_blank');
                }

                document.body.appendChild(tempLink);
                tempLink.click();
                window.URL.revokeObjectURL(url);

                toastr.success('Sucessfully generated marketing question report');
                this.setState({isLoading: false, isLoadingFinished: true});
                actions.clearMarketingQuestionReportDates();
            })
            .catch(() =>
                toastr.error('An error occurred while generating marketing question report')
            );
    };

我很震惊。然后我不知道如何测试整个获取调用

目前我有什么

    describe('<MarketingQuestionReportPage />', () => {
    beforeEach(() => {
        const fecthSpy = jest.spyOn(window, 'fetch').mockReturnValue(() =>
            Promise.resolve({
                blob: () =>
                    Promise.resolve({
                        size: 6682,
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    }),
            })
        );
    });


    test('generateExcelFile', () => {
        const props = {
            state: fromJS({
                config: {
                    marketingQuestionReport: {
                        dateFrom: '2019-01-01',
                        dateTo: '2021-03-21',
                    },
                },
            }),
            actions: {
                clearMarketingQuestionReportDates: jest.fn(),
            },
        };
        const tree = shallowSetup(props);
        tree.instance().generateExcelFile();
        tree.fecthSpy.toHaveBeenCalled();
    });
});

我制作了我的组件的一个实例 - 我已经准备好该调用所需的道具,我将它们发送到我的 instance.After 我调用我的方法 - generateExcelFile();

在我的报道中,除了 fetch 调用外,所有内容都是免费的。我不知道如何解决这个问题。请帮助

在使用 jest.spyOn(object, methodName) 渲染组件之前,您需要创建 fetchspy

test('generateExcelFile', () => {
    const fetchSpy = jest.spyOn(window, "fetch").mockReturnValue(Promise.resolve({
      blob: () =>
        Promise.resolve({
          size: 6682,
          type:
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        }),
      })
    );
    //...
    const tree = shallowSetup(props);
    tree.instance().generateExcelFile();
    expect(fetchSpy).toHaveBeenCalled();
});

在您的测试中,您可以检查 fecthSpy 是否已被调用