吃雞游戲
2023-09-28 17:33:52
所以我試圖用SinonJS 存根請求。在每次測試之前,它應該使用已解決的虛假信息來模擬請求,但它似乎沒有按預期工作。嘗試使用 解決Promise.resolve,但它也無法按我的預期工作。這是測試代碼: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); });});這是我收到的錯誤: 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)); }我在這里做錯了什么?任何幫助深表感謝。
1 回答

holdtom
TA貢獻1805條經驗 獲得超10個贊
這是因為你的第二個提交函數調用是在 Promise then 方法內部。
您需要等待 users.actions.list()。
例如:
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);
});
添加回答
舉報
0/150
提交
取消