A guide to resolving a sinonJS stub issue

Trying to stub a request with SinonJS has been a challenge for me. I set up the mock request before each test to use fake data, but it's not working as expected. I attempted to use Promise.resolve for resolving, but that didn't work out either.

Below is the code for the test:

describe("Store | Users actions", () => {
  let commit = null;
  let page = 1;
  let itemsPerPage = 2;

  const users_response = {
    status: 200,
    data: [{
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1f2c8cfc2c4d3c4e1c0d1d3c8cd8fc3c8db">[email protected]</a>"
    },
    {
      "id": 2,
      "name": Ervin Howell",
      "username": Antonette",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b68535a55555a7b565e575248485a154f4d">[email protected]</a>"
    }]
  };

  beforeEach(() => {
    commit = sinon.spy();
    sinon
      .stub(api.users, "list").resolves();
  });

  afterEach(() => {
    api.users.list.restore();
  });

  it("should list users", () => {
    users.actions.list({ commit }, { page, itemsPerPage });
    expect(commit).to.have.been.calledWith("UNSET_ERROR");
    expect(commit).to.have.been.calledWith("GET_PAGINATED", users_response);
  });
});

The error message I'm encountering is as follows:

  1) Store | Users actions
       should list users:
     AssertionError: expected spy to have been called with arguments GET_PAGINATED, {
  data: [{ email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34675d5a57514651745544465d581a565d4e">[email protected]</a>", id: 1, name: "Leanne Graham", username: "Bret" }, { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8cdfe4ede2e2edcce1e9e0e5ffffeda2f8fa">[email protected]</a>", id: 2, name: "Ervin Howell", username: "Antonette" }],
  status: 200
}
"UNSET_ERROR" "GET_PAGINATED"
{
  data: [{ email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9fccf6f1fcfaedfadffeefedf6f3b1fdf6e5">[email protected]</a>", id: 1, name: "Leanne Graham", username: "Bret" }, { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aaf9c2cbc4c4cbeac7cfc6c3d9d9cb84dedc">[email protected]</a>", id: 2, name: "Ervin Howell", username: "Antonette" }],
  status: 200
}
      at Context.<anonymous> (dist/js/webpack:/tests/unit/store/users.spec.js:184:1)
list({ commit }, { page, itemsPerPage, sort, search }) {
      commit("UNSET_ERROR");

      return api.users
        .list(page, itemsPerPage, sort, search)
        .then((users) => commit("GET_PAGINATED", users.data))
        .catch((error) => commit("SET_ERROR", error));
    }

I would greatly appreciate any assistance in identifying where I might be going wrong here.

Edit: added list function

Answer №1

It seems like the issue lies in the placement of your second commit function call within the Promise then method.

To resolve this, make sure to await the users.actions.list() function.

Here is an example of how you can implement this:

  beforeEach(() => {
    commit = sinon.spy();
    // Note: include users_response here.
    sinon.stub(api.users, "list").resolves(users_response);
  });

  // Make sure to use async keyword here.
  it("should list users", async () => {
    // Don't forget to use await keyword here.
    await users.actions.list({ commit }, { page, itemsPerPage });
    expect(commit).to.have.been.calledWith("UNSET_ERROR");
    // Note: Specify 'data' property in the expectation because it is called with: users.data.
    expect(commit).to.have.been.calledWith("GET_PAGINATED", users_response.data);
  });

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

Nested JSON file retrieval by Axios

I am having trouble retrieving the 'title' from my JSON file. I have been trying to access it through the 'results - metaData' path, but so far without success. The 'resultPacket' is returning data, but accessing 'metaDat ...

triggering e.stopImmediatePropagation() within an onclick event handler

Is there a way to retrieve the event object from an onclick attribute? I attempted the following: <a href="something.html" onclick="function(e){e.stopImmediatePropagation();}">Click me</a> In addition, I tried this: <a href="something.ht ...

Ways to verify that window.open is being invoked from a React component

In my React component, I have a set of nested components, each with its own checkbox. The state hook rulesToDownload starts as an empty array and dynamically adds or removes IDs based on checkbox selection. Upon clicking the 'download' button, t ...

What is the best method for transferring images to a node.js server using Axios?

Is there a method to utilize axios for sending an array of images or a single image to node? My current axios code (implemented in react js on the frontend): onFormSubmit(event){ event.preventDefault(); let payload = this.state; console.log(" ...

In order to display a particular view whose filename is determined by the database, I must develop a function within the controller. - laravel

In my system, there is a default page and 4 models that can be changed. The filename corresponding to each model is stored in the database, which is where I encountered some issues. I am unable to pass the variable that determines the filename to the retur ...

Issue with joining tables in query on Cordova Mobile app

I have 2 queries that will return results which I plan to use in JSON format. The first query is $query = "SELECT * FROM info_location WHERE location_id=".$id.""; and the second query $query = "SELECT t1.location_id,t1.street,t1 ...

Setting up ESLint for TypeScript with JSX configuration

I am encountering problems with TypeScript configuration. Below is the code snippet from my tsconfig.json: { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLib ...

The smooth scrolling feature fails to function properly in Lenis when clicking on links with specified IDs

Is there a reason why the scroll-behavior: smooth property doesn't function properly when Lenis library for smooth scrolling is included? It seems to work fine when the Lenis code is commented out, but once it's added back in, the scrolling isn&a ...

I am encountering an issue with my Javascript file not running due to a bigint error

I'm attempting to utilize @metaplex/js for NFT minting. Usually, my .js files function correctly, but when I execute the file, this particular error arises. bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?) The meaning of ...

Enhance Laravel 5 by integrating browserify into the Elixir build process

My workflow for transforming coffee to js using browserify, browserify-shim, and coffeeify looks like this: I work with two main files: app.coffee and _app.coffee, designated for frontend and backend respectively. These files are located in resources/coff ...

AngularJS property sorting: organize your list by name

I have a complicated structure that resembles: { 'street35':[ {'address154': 'name14'}, {'address244': 'name2'} ], 'street2':[ {'address15& ...

Converting an onclick event to onsubmit: Tips for doing it right

Recently, I had to add validation to a file upload form for our Google Drive. After some research, I discovered that using onsubmit instead of onclick was the way to go. However, when I made the switch from onclick to onsubmit, the validation worked but t ...

Tips for maintaining the browser scroll bar at the top when switching routes in AngularJS

How can I ensure that the scrollbar is always at the top when a user is redirected to a different page after scrolling down on the home page? The autoscroll feature in the code below doesn't seem to be working. Any suggestions would be greatly appreci ...

What is the process for inserting a watermark onto an image as it is being retrieved from Firebase?

I am developing a React website where I need to implement a feature that adds a watermark to an image when it is retrieved from Firebase storage. Is there a way to apply a watermark while accessing the image from the storage? I have already looked into Ho ...

Cart cannot function as a constructor

I'm currently learning express.js and trying to implement a shopping cart/session functionality into my project. Below is the code I have written so far, with a question at the end. Here is my cart.js: // Ensure that the file is required correctly b ...

Problems with Google Maps Event Tracker

I recently inherited a section of code that utilizes the Google Maps API to place markers on a map along with information windows. Below is an excerpt from the code responsible for creating the markers and setting up event listeners: if(markers.length > ...

What is the method to retrieve the information from a JSON response of a POST request in a Next/React application?

I am currently leveraging the Next.js API route to manage a POST request and subsequently send a response back to the frontend. To verify this process, I have utilized the Rapid API client extension and confirmed that a response is indeed being sent to the ...

Transmit information to PHP script using JavaScript

I am facing an issue with sending form data to another PHP file. While the process is working, the problem lies in the fact that once the data is submitted, the page does not redirect to the specific page as intended. It seems like it doesn't work th ...

Utilizing Ajax for dynamic PHP result determination

HTML CODE <div class="card text-center pricing-card mb-20"> <ul class="list-group list-group-flush"> <?php $gbewas = mysqli_query($con,"SELECT * FROM price"); while($okks = mysqli_fetch_array($gbewas)) { ?> <li cla ...

Messy code appeared when sending an AJAX post to JBoss EAP 7 without using encodeURIComponent

Initially, the project functions smoothly on tomcat using UTF-8 and jboss eap 6 with UTF-8 page encoding as well. Additionally, the jboss configuration includes: <servlet-container name="default" default-buffer-cache="default" stack-trace-on-error="loc ...