【发布时间】:2019-02-22 08:35:01
【问题描述】:
我正在尝试使用 mocha 和 sinon 来测试一段使用 AWS 服务的代码。代码下方:
exports.init = ({ athenaClient }) => {
const command = {};
command.execute = sqlCommand => {
const params = {
QueryString: sqlCommand,
QueryExecutionContext: {
Database: process.env.ATHENA_DB || "default"
}
};
return athenaClient.startQueryExecution(params).promise();
};
return command;
};
在我的测试中,我正在模拟 athena 客户端并将其注入函数中,并且我想测试方法 startQueryExecution 是否使用作为输入发送的 sqlCommand 调用。所以我一直在尝试在它上面创建一个存根。
这是我的测试:
const AWS = require("aws-sdk");
const AWS_MOCK = require("aws-sdk-mock");
const sinon = require("sinon");
const expect = require("chai").expect;
describe("Executes a sql command in Athena", async done => {
process.env.ATHENA_DB = "default";
it("the sqlCommand is sent to startQueryExecution", async () => {
const SQL_COMMAND = "DROP TABLE IF EXISTS dataset_test PURGE;";
const athenaClient = {
startQueryExecution: params => ({})
};
const executeAthenaQueryCommand = require("../commands/executeAthenaQueryCommand").init(
{
athenaClient
}
);
sinon.stub(athenaClient, "startQueryExecution");
sinon.stub(executeAthenaQueryCommand, "execute");
const result = await executeAthenaQueryCommand.execute(SQL_COMMAND);
sinon.assert.calledWith(executeAthenaQueryCommand.execute, SQL_COMMAND);
const expectedResult = {
QueryString: SQL_COMMAND,
QueryExecutionContext: {
Database: "default"
}
};
sinon.assert.calledWith(athenaClient.startQueryExecution, expectedResult);
});
after(() => {});
});
但是我得到了错误:
AssertError: expected startQueryExecution to be called with arguments
at Object.fail (node_modules/sinon/lib/sinon/assert.js:104:21)
at failAssertion (node_modules/sinon/lib/sinon/assert.js:61:16)
at Object.assert.(anonymous function) [as calledWith] (node_modules/sinon/lib/sinon/assert.js:86:13)
at Context.it (test/executeAthenaQueryCommand.spec.js:37:22)
at <anonymous>
有什么帮助吗?
【问题讨论】:
-
您正在存根
execute方法,但没有指定它应该返回/解决什么。看来你可能不想存根execute如果它正在做一些处理创建一个参数发送到startQueryExecution
标签: javascript unit-testing mocha.js sinon