如何在serverless-mocha-plugin中模拟单元测试的功能

时间:2018-05-28 11:30:03

标签: node.js unit-testing aws-lambda mocha aws-serverless

我正在使用aws lambda函数和nodejs我正在尝试测试以下函数。

module.exports.handler = (event, context, callback) => {

var host = environment.set_environment(env);

if (event.body[0].value) {
var cid= event.body[1].customerID;
var loginResponse = loginMethods.login(host,cid);

loginResponse.then(function (loginResult) {
  if (loginResult.hash) {
    console.log("login success");
    var Response = requestMethod.callAPI(event.body, loginResult.hash);
    Response .then(function (Result) {
      console.log('successfulll');



    }, function (error) {
      console.log('failure response');

    })
  } else {
    console.log("login response with no token");

  }
}, function (error) {
  console.log('login failure response');

})

} else {
  callback(null, responseMethods.error('Invalid request'));
}

};

当我调用此函数进行单元测试时,我想模拟在此函数中调用的其他函数

例如在这一行中

var loginResponse = loginMethods.login(host,cid);

在单元测试中,我不想调用实际函数我只想调用一个模拟函数进行单元测试 我是从UI背景中实现同样的东西,即在单元测试中模拟一个函数,我们可以在导入时轻松完成。

我有一种方法可以在nodejs中模拟函数

1 个答案:

答案 0 :(得分:0)

我找到了一种方法来使用nodejs来模拟无服务器moca-plugin中的函数

可以使用sinonjs http://sinonjs.org/

来完成

以上是上述功能的示例 为了模拟loginMethods

const loginPromise = new Promise(function (resolve, reject) {
  const loginRes = {

    "status": "success",
    "hash": "U2_a5da71a9-4295-48e7-b427-843c17c8cae3",
    "firstName": "Guest",
    "lastName": "G",
  };
  resolve(loginRes);
});

var loginMock = sinon.mock(loginMethods);
loginMock.expects('login').withArgs(arg1, arg2).returns(loginPromise);

这样一来测试时这个函数会调用它只会调用mock函数而不是原来的函数而且响应也会被模拟响应