javascript - 如何解决 sinonJS 存根?
问题描述
所以我试图用 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": "Sincere@april.biz"
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv"
}]
};
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: "Sincere@april.biz", id: 1, name: "Leanne Graham", username: "Bret" }, { email: "Shanna@melissa.tv", id: 2, name: "Ervin Howell", username: "Antonette" }],
status: 200
}
"UNSET_ERROR" "GET_PAGINATED"
{
data: [{ email: "Sincere@april.biz", id: 1, name: "Leanne Graham", username: "Bret" }, { email: "Shanna@melissa.tv", 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));
}
我在这里做错了什么?任何帮助深表感谢。
编辑:添加列表功能
解决方案
那是因为您的第二个提交函数调用在 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);
});
推荐阅读
- php - mysli_fetch_assoc 中的数组减法
- angular - 重写 Angular 8 的引导程序下拉菜单
- javascript - svg.circle 上的 mouseover 和 mouseout 事件
- java - 上传文件时出现 HTTP 错误 400“所需的请求部分‘文件’不存在”
- php - 我如何通过控制器更改 Laravel 6.0 中的 .env 变量?
- javascript - 尽管返回错误语句,JavaScript 仍提交表单
- linux - Boost 托管映射文件 std::unordered_map Linux 分段错误
- mysql - 如何在 mysql 视图中设置列的排序规则?
- html - Instascan 选择 camara 扫描 qr
- php - 从 AWS DynamoDB 检索 PHP 页面中的数据中删除的 XML 标签