Search code examples
javascriptunit-testingvue.jsvuexsinon

How to resolve sinonJS stub?


So I'm trying to stub a request with SinonJS. Before each test it should mock the request with resolved fake info, but it doesn't seem to work as expected. Tried resolving with Promise.resolve, but it also doesn't work as I expected.

Here's the test code:

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": "[email protected]"
    },
    {
      "id": 2,
      "name": "Ervin Howell",
      "username": "Antonette",
      "email": "[email protected]"
    }]
  };

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

This is the error i'm getting:

  1) Store | Users actions
       should list users:
     AssertionError: expected spy to have been called with arguments GET_PAGINATED, {
  data: [{ email: "[email protected]", id: 1, name: "Leanne Graham", username: "Bret" }, { email: "[email protected]", id: 2, name: "Ervin Howell", username: "Antonette" }],
  status: 200
}
"UNSET_ERROR" "GET_PAGINATED"
{
  data: [{ email: "[email protected]", id: 1, name: "Leanne Graham", username: "Bret" }, { email: "[email protected]", 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));
    }

What am I doing wrong here? Any help is much appreciated.

Edit: added list function


Solution

  • That is because your second commit function call is inside Promise then method.

    You need to await for users.actions.list().

    For example:

      beforeEach(() => {
        commit = sinon.spy();
        // Note: add users_response here.
        sinon.stub(api.users, "list").resolves(users_response);
      });
    
      // Use async here.
      it("should list users", async () => {
        // Use await here.
        await users.actions.list({ commit }, { page, itemsPerPage });
        expect(commit).to.have.been.calledWith("UNSET_ERROR");
        // Note: expect with property data, because called with: users.data.
        expect(commit).to.have.been.calledWith("GET_PAGINATED", users_response.data);
      });