Testing HTTP requests on a form click in Vue.js 2 - Let's see how

Within my component, I have the following method:

   methods:{
      ContactUs(){
            this.$http.post("/api/contact-us").then((res)=>{
               ///do new stuff
            },(err)=>{
               //do new stuff
            })
        },

    }

Now, I am trying to test if the method functions correctly.

In my test script, I implemented the following:

 const wrapper = mount(ContactForm);

it("Contact us method should return a 200 response ", () => {
    wrapper.vm.ContactUs().then((res) => {
        expect(res.data).toEqual(res);
    })
    //await flushPromises();
});

However, the test is failing and the error seems to be related to the 'this.$http.post' line...

How should I go about properly testing the above function?

Answer №1

To enable chaining with a .then() method, ContactUs function should return a promise. Using this.$http.post already provides a promise, so simply return its result from ContactUs to allow for seamless chaining in your test.

  ContactUs(){
        return this.$http.post("/api/contact-us").then((res)=>{
           ///do new stuff
        },(err)=>{
           //do new stuff
        })
    },

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

Managing a digital timepiece within a multiplayer gaming environment

I'm currently developing a fast-paced game where players control a block resembling a clock. To accurately calculate the time taken by each player to make moves, I store the start time of the game and record the timestamp of every move in the databas ...

The promise in app.js at line 51471 was caught with an error stating that the navigation from "/customer/login" to "/customer/dashboard" was cancelled due to a new navigation instance

After logging in, I am trying to redirect to another page using router push, but encountering an error. app.js:51471 Uncaught (in promise) Error: Navigation cancelled from "/customer/login" to "/customer/dashboard" with a new navigation ...

Whenever a new entry is made into the textfield, the onChange feature triggers a reset on the content within the textfield

I'm experiencing an issue while creating a SignUp authentication page with Firebase. Every time I try to input text in the text field, it gets reset automatically. I have been unable to identify the root cause of this problem. It seems to be related t ...

(Is it even necessary to use a timezone library for this straightforward scenario?)

As I delve into the realm of time zones for the first time, I've heard tales of how challenging it can be for developers. To ensure I am on the right track, I am posing this question as a safeguard to make sure nothing is overlooked. My scenario is q ...

The issue with text color not displaying properly within a Material-UI Theme

While designing a color theme using Material-UI, I specified the contrast text as white (#fff). Surprisingly, it seems to work for buttons with the primary color but not for those with the secondary color. I attempted overrides following the suggestions p ...

A specialized identifier for nested objects in a React component

I am currently working with a JSON data structure that looks like this: [ [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ], [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ...

Implementing the 'keepAlive' feature in Axios with NodeJS

I've scoured through numerous sources of documentation, Stack Overflow threads, and various blog posts but I'm still unable to make the 'keepAlive' functionality work. What could I be overlooking? Here's my server setup: import ex ...

How can I ensure my game or website fits perfectly on the screen without any need

I have recently developed a fun Erase-A-Man game that is optimized for mobile devices. However, I am facing an issue where users need to scroll to view all the letters on their screens. My goal is to make the game fit perfectly on all phone screen sizes so ...

Updating image source dynamically with Flask

I am currently developing a face detection application using Flask. I aim to have the detected faces displayed in real-time on the HTML page. For the JavaScript aspect, I am utilizing getUserMedia to live stream camera images from the client to the server ...

The karma test appears as "passed" in IntelliJ, even though there are remaining errors present, leading to a failure in the CI/CD process

Currently working on an Angular project, my goal is to ensure all tests turn green. Surprisingly, they all passed on my end, but the CI/CD process (Teamcity) failed. Upon checking the log in my IntelliJ IDE, it was revealed that certain tests actually repo ...

Can multiple `npm install` commands run at the same time?

Is it possible to have concurrent runs of npm install, or will they conflict on shared resources and create potential race conditions? Analyzing the code might not provide a clear answer, but for those working on developing npm, this is likely an implicit ...

Running Javascript based on the output of PHP code

I have been working on my code with test.php that should trigger some Javascript when my PHP code, conditional.php, detects input and submits it. However, instead of executing the expected "Do Something in Javascript," it outputs "Not empty" instead. I fin ...

using javascript to create two choices

I am facing a small complication between two select options in my javascript code. Here is the snippet of my javascript: function displayVals() { var singleValues = $("select option:selected").text(); //to stay selected $("#hiddenselect").val(s ...

How can I globally expose my APIService.js class to Vue JS components without needing to import it in each individual component?

Most of my components rely on interactions with my apiservice.js class, which uses Axios to handle http requests based on the method called. I understand that this may not be the recommended approach, but in every component, I include the following code: ...

Unable to open fancybox from a skel-layer menu

Seeking assistance with integrating a Fancybox inline content call from a Skel-layer menu (using the theme found at ) <nav id="nav"> <ul> <li><a href="#about1" class="fancybox fancybox.inline button small fit" >about< ...

Pressing the HTML button will reveal the cart details in a fresh display box

I have been working on setting up a button to display the items in the shopping cart. I have successfully created the cart itself, but now I am facing the challenge of creating a button called showYourCart that will reveal a box containing the cart detai ...

"Creating a mock method in a test file located in a separate directory using Python

Encountering challenges while trying to mock a method, as the mock function is actually overwriting it. In app/tests/test_file.py we currently have the following unit test: @mock.patch('app.method', return_value='foo') def test(self, ...

ES6 promises: the art of connecting functions with parameters

Looking for a way to chain functions with delays? Here is an example of what I have tried: Promise.resolve() .then(setKeyframe('keyframe-0')) .then(delay(3000)) .then(setKeyframe('keyframe-1')) .then(delay(3000)) .then(setKeyframe(&apo ...

Update the content of a div on the WordPress homepage with the click of a button

Hey there, I'm currently working on customizing the Boutique theme for a website. My goal is to add two buttons to the home page that will display different sets of products when clicked. I've been attempting to use the visibility property, but h ...

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...