我是 node js 和一般测试的新手。我设法使用 sinon 来存根我的函数等,但现在我必须测试一个根据事件(onSuccess,onFailure)发送回调的函数。
这是我需要测试的代码。
var AWSCognito = require('amazon-cognito-identity-js');
exports.getToken = function (options, callback) {
var poolData = {
UserPoolId : options.UserPoolId,
ClientId : options.ClientId,
};
var authenticationData = {
Username : options.username,
Password : options.password,
};
var userPool = new AWSCognito.CognitoUserPool(poolData);
var authenticationDetails = new AWSCognito.AuthenticationDetails(authenticationData);
var userData = {
Username : options.username,
Pool : userPool
};
var cognitoUser = new AWSCognito.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
callback(null, {idToken: result.getIdToken().getJwtToken()});
},
onFailure: function (err) {
callback(err);
},
});
}
这就是我到目前为止所做的。
var proxyquire = require('proxyquire'); var should = require('should'); var sinon = require('sinon'); var AWSCognito = require('amazon-cognito-identity-js');
describe('authentication tests', function () { var expectedResult;
it('should invoke a lambda function correctly', function (done) {
var options = {
username: 'username1',
password: 'pwd',
UserPoolId : 'user_Pool',
ClientId : 'clientId'
};
var expectedResult = {
idToken: '123u'
};
var authenticateUserStub = sinon.stub().yieldsTo('onSuccess');
var testedModule = proxyquire('../../../api/helpers/authentication.js', {
'amazon-cognito-identity-js': {
'CognitoUser': function () {
return {
authenticateUser: authenticateUserStub
}
}
}
});
testedModule.getToken(options, function (err, data) {
// should.not.exist(err);
// data.should.eql(expectedResult);
done();
}); }); });
这就是我得到的错误
TypeError: Cannot read property 'getIdToken' of undefined
at onSuccess (api/helpers/authentication.js:25:38)
at callCallback (node_modules/sinon/lib/sinon/behavior.js:95:18)
at Object.invoke (node_modules/sinon/lib/sinon/behavior.js:128:9)
at Object.functionStub (node_modules/sinon/lib/sinon/stub.js:98:47)
at Function.invoke (node_modules/sinon/lib/sinon/spy.js:193:47)
at Object.proxy [as authenticateUser] (node_modules/sinon/lib/sinon/spy.js:89:22)
at Object.exports.getToken (api/helpers/authentication.js:23:15)
at Context.<anonymous> (test/api/helpers/authenticationTests.js:37:18)
看起来它正在进入 onSuccess 函数,然后它无法识别 getIdToken。但它在测试中走得太远了,不是吗?我只想存根/模拟 authenticateUser 并返回一个虚拟响应。
我怎样才能告诉 sinon 在 'onSuccess' 上给我回一个回调,而不涉及回调的细节?
谢谢你的帮助