Issue with Jest: Mocked function not found by Vue Component

I am currently in the process of mocking an ES6 class that is being utilized within my Vue Component:

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

In my attempt to follow this guide, I believe there may be a syntax issue with my mock implementation:

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(); 
        mockGetUploadedFiles.mockClear();
    });
    describe('renders correct markup:', () => {
        it('without any uploaded files', () => {
            const wrapper = mount(FileDownloadList, {});
            expect(wrapper).toMatchSnapshot();
        });
    });
});

While this test passes, upon inspecting the snapshot, I discovered that the API call failed and displayed the following error message:

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

Could someone kindly point out what might be wrong with my function mock? Thank you for your assistance!

Answer №1

After reviewing my code, it appears that there were a few issues:

Simulating the API

Utilizing an internal mockImplementation seems to be causing some complications. It may not be necessary if you do not require the extra mock functionality.

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

Updates to the test

Both flushPromises and nextTick are essential for this process.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The chosen option does not equal the value retrieved by using jQuery's

I am perplexed by the situation at hand. It seems that there is a discrepancy in the selected option of my select element. Despite appearing as the empty default option on top, the inspected element reveals it displaying a value of 13. https://i.sstatic.n ...

The process of converting a response into an Excel file

After sending a request to the server and receiving a response, I am struggling with converting this response into an Excel file. Response header: Connection →keep-alive cache-control →no-cache, no-store, max-age=0, must-revalidate content-dispositio ...

Node.js script terminated: Process concluded with an exit code 139 due to being interrupted by signal 11 (SIGSEGV)

I'm encountering a frustrating issue with my script - it keeps crashing and the debugger isn't able to pinpoint the error. I've attempted using try-catch blocks, but they just don't seem to work. Any recommendations on how I can better ...

What is the best way to initialize firebase with context in a React application?

Currently, I'm following a tutorial at this link: I've hit a roadblock at the following step: Context.jsx import React from 'react'; const FirebaseContext = React.createContext(null); export default FirebaseContext; index.js impo ...

Using jQuery to refresh a div element

I am struggling with updating the "right" div in my jsp page using the script below. Despite being contained in a single file, the update does not seem to work. Any assistance is appreciated. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//E ...

hitting the value of the text input

Is there a way to strike through only the first word in an input box of type text, without editing the html? I've tried using css text-decoration: line-through; but it's striking both words. Any suggestions on how to achieve this using javascript ...

"Troubleshooting a Node.js JWT issue in a React.js

I've been diving into backend development and recently created some small APIs. They all function perfectly in Postman, but I encountered an issue when attempting to execute this particular call const onSubmit = async () => { try { setIsL ...

Using Asynchronous JavaScript and XML (AJAX) to make calls to a web service

My program is showing an internal server error var parameters = "<?xml version='1.0' encoding='utf-8'?>" + "<soap:envelope xmlns:xsi='ttp://www.w3.org/2001/xmlschema-instance' xmlns:xsd='http://www.w3. ...

Breaking up and processing a given string in JavaScript: Splitting and token

When it comes to dealing with this specific JavaScript requirement, the challenge lies in working with a string such as: “ [ condition12 (BRAND) IN 'Beats by Dr. Dre & D\’Silva of type Band’ of type 'IDENTIFIER_STRING’ ] ...

Tips for validating email addresses and enforcing minimum length requirements

In order to validate email input for the correct format and ensure minimum length validations for first name and password, I am looking to utilize only bootstrap. While I have successfully implemented required field validations for the inputs, I am unsure ...

.sort method will produce a map with just one element

I have a map that contains 10 entries displayed in the first 10 lines of the "logs" section below. The map is populated with values in the following manner: const featuresMap = {}; for (const feature of features) { featuresMap[feature.getName()] = feat ...

What is the regular expression that allows numbers between 1 and 24, including decimals?

Can anyone help me create a regex expression that only allows numbers between 1 and 24, with up to 2 decimal places? The numbers should range from 1 to 24, as well as include decimals like 1.00, 1.01, 1.02, all the way up to 24.99. ...

Error: JSON input ended unexpectedly and was not caught in the promise block

This code snippet showcases the add to cart functionality, which involves inserting data into a database. Although the database insertion works correctly, an error occurs every time the "add to cart" button is clicked (despite still successfully adding to ...

Creating a basic bar graph using d3.js with an array of input data

In my dataset, I have an array of form data that includes items like 'Male', 'Female', 'Prefer Not To Say'. I want to create a simple bar chart generator using D3.js that can display the percentages or counts of each item in t ...

Streamline your VueJS code by utilizing a single computed property to define multiple dynamic attributes

So I have this interesting piece of HTML: <a href="javascript:">Link text</a> I'm looking to dynamically add the data-tooltip and title attributes based on a condition: <a href="javascript:" data-toggle="tooltip" title="Some tooltip ...

Steps for integrating the -toDataURL() method on a node.js server

As a newcomer to webgl implementation in my project, I am facing an issue with the .toDataURL() function while using the node-webgl wrapper on the server side. The error I encounter states that .toDataURL() is undefined. More information on this error can ...

Is it possible to create a return using messageEmbed in Discord?

I have been working on creating a Discord bot that responds to the ! status command with the server status. I took inspiration from this existing bot. The only change I made was to ensure that the bot replies immediately to the ! status command without re ...

Interactive Timekeeping Tool with AngularJS Alarm Feature

I have successfully implemented the functionality to display the system time and date. Additionally, I have set up textboxes for users to input the time they want to set as their first alarm. My current goal is to trigger a particular action once the syst ...

Troubleshooting encoding problems with Google Cloud's Speech-to-Text API using Node.js

I'm currently working on a project that involves capturing audio from a user's microphone and sending it to a server for translation using Google's Speech-to-Text API. I am utilizing navigator.mediaDevices.getUserMedia() to access the audio, ...

Can TSLint and ESLint give a warning when a function is accessed as a property?

There have been instances where I've made this specific mistake, and I'm curious if there are any ESLint or TSLint rules in place that could detect it. if (this.isBrowser && this.imageURL) {.....} private isBrowser(): boolean{ retur ...