如何模拟 serverless-mocha-plugin 中单元测试的功能
How to mock function for unit testing in serverless-mocha-plugin
我正在使用 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 背景来实现同样的事情,即在 angular 中模拟单元测试中的函数,我们可以在导入时轻松完成。
我有办法在 nodejs 中模拟函数
我找到了一种使用 nodejs 在 aws 的 serverless-mocha-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);
这样在测试什么时候调用这个函数时它只会调用模拟函数而不是原始函数并且响应也将是模拟响应
我正在使用 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 背景来实现同样的事情,即在 angular 中模拟单元测试中的函数,我们可以在导入时轻松完成。
我有办法在 nodejs 中模拟函数
我找到了一种使用 nodejs 在 aws 的 serverless-mocha-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);
这样在测试什么时候调用这个函数时它只会调用模拟函数而不是原始函数并且响应也将是模拟响应