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

时间:2019-08-26 09:23:05

标签: javascript unit-testing vue.js jestjs

我正在模拟在Vue组件中使用的ES6类:

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

我一直在跟踪this文档,但我认为我的语法与我的语法略有出入:

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();
        });
    });
});

此测试通过。但是,在快照中,我可以看到调用API失败并显示以下错误消息:

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

我对函数模拟做了什么错?预先感谢!

1 个答案:

答案 0 :(得分:0)

我的代码似乎存在一些问题:

模拟API

使用内部TASK [See result] ******************************************************************************************************************************************************************************************************************************************************* ok: [localhost] => { "groups": { "all": [ "192.168.13.236", "192.168.13.201", "192.168.13.237" ], "cluster": [ "192.168.13.236", "192.168.13.201", "192.168.13.237" ], "masters": [ "192.168.13.236" ], "nodes": [ "192.168.13.201", "192.168.13.237" ], "ungrouped": [] } } 似乎会引起问题,如果您不需要其他模拟功能,则不需要。

mockImplementation

更改为测试

flushPromisesjest.mock('@/apps/gb-data/webapi/DataUploadService', () => ({ getUploadedFiles() { return Promise.resolve({ uploaded_files: {} }); }, })); 都是必需的。

nextTick