简体   繁体   English

开玩笑:Vue组件找不到模拟函数

[英]Jest: Vue Component can't find mocked function

I'm mocking a ES6 class which is used inside my Vue Component: 我正在模拟在Vue组件中使用的ES6类:

export default class DataUploadApi {
    // Get uploaded files
    static async getUploadedFiles() : Promise<Object> {
        return WebapiBase.getAsync({uri: DATA_UPLOAD_ENPOINTS.FILES});
    }
}

I've been following along with this document, but I think my syntax is slightly off with my mock: 我一直在关注文档,但是我认为我的语法与我的语法略有出入:

import { mount } from '@vue/test-utils';
import DataUploadApi from '../webapi/DataUploadService';
import FileDownloadList from '../components/file-download-list.vue';

const mockGetUploadedFiles = jest.fn().mockResolvedValue({json: JSON.stringify(uploadedFilesObj)});
jest.mock('../webapi/DataUploadService', () => jest.fn().mockImplementation(() => ({getUploadedFiles: mockGetUploadedFiles})));

describe('file-download-list component', () => {
    beforeEach(() => {
        // @ts-ignore
        DataUploadApi.mockClear(); // https://stackoverflow.com/a/52707663/1695437 dont use @ imports on mocks.
        mockGetUploadedFiles.mockClear();
    });
    describe('renders correct markup:', () => {
        it('without any uploaded files', () => {
            const wrapper = mount(FileDownloadList, {});
            expect(wrapper).toMatchSnapshot();
        });
    });
});

This test passes. 该测试通过。 However, in the snapshot I can see that the API called failed with this error message: 但是,在快照中,我可以看到该API调用失败,并显示以下错误消息:

<p>
    _DataUploadService.default.getUploadedFiles is not a function
</p>

What have I done wrong with the function mock? 我对函数模拟做了什么错? Thanks in advance! 提前致谢!

There seemed to be a few issues with my code: 我的代码似乎存在一些问题:

Mocking the API 模拟API

Using an internal mockImplementation seems to cause issues, and is not required if you don't need the additional mock functionality. 使用内部mockImplementation似乎会引起问题,如果您不需要其他嘲笑功能,则不需要这样做。

jest.mock('@/apps/gb-data/webapi/DataUploadService', () => ({
    getUploadedFiles() {
        return Promise.resolve({ uploaded_files: {} });
    },
}));

Changes to the test 测试变更

Both flushPromises and nextTick are required. flushPromisesnextTick都是必需的。

 it('with uploaded files', async () => {
     const wrapper = mount(FileDownloadList, {
         stubs: fileDownloadListStubs,
     });
     await flushPromises();
     await wrapper.vm.$nextTick();
     expect(wrapper).toMatchSnapshot();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM