我正在尝试使用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客户端并将其注入到函数中,并且我想测试使用作为输入发送的sqlCommand调用方法startQueryExecution。因此,我一直在尝试在其上创建存根。
这是我的测试
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>
请帮忙吗?
答案 0 :(得分:1)
您几乎正确了。纠正测试的一些注意事项是
在startQueryExecution存根中添加返回
这是必须的,因此正确执行execute
函数以返回promise。
sinon.stub(athenaClient, "startQueryExecution").returns({ promise: () => Promise.resolve() });
删除执行方法的存根
这是我们要测试的真实方法,我们将在后续行中对其进行调用,因此请勿对它进行存根处理。
sinon.stub(executeAthenaQueryCommand, "execute"); // remove this
sinon.assert.calledWith(executeAthenaQueryCommand.execute, SQL_COMMAND); // remove this
因此最终的测试文件将是
describe("Executes a sql command in Athena", async done => {
...
it("the sqlCommand is sent to startQueryExecution", async () => {
...
sinon.stub(athenaClient, "startQueryExecution").returns({ promise: () => Promise.resolve() }); // add returns
const result = await executeAthenaQueryCommand.execute(SQL_COMMAND);
const expectedResult = {
QueryString: SQL_COMMAND,
QueryExecutionContext: {
Database: "default"
}
};
sinon.assert.calledWith(athenaClient.startQueryExecution, expectedResult);
});
after(() => {});
});