node.js - 测试 AWS 服务未按预期工作时,我的 Node.JS 项目中的 sinon.spy
问题描述
在我的 Node.JS 项目(Angular 5 项目的后端)中,我创建了一个处理 AWS 身份验证的服务......我称之为awsAuthenticationService
. 一切正常,但我现在需要对其进行测试。在我的awsAuthenticationService.js
我有以下具有一些次要逻辑的方法,然后调用“ cognitoIdentityServiceProvider
”提供的方法。这是我的代码片段(我真的减少了这个)
constructor() {
this._cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider(this.cognitoConfig);
}
toggleUserAccess(userName, type) {
const params = {
Username: userName,
UserPoolId: this.cognitoConfig.userPoolId
};
if (type === null) {
return this._cognitoIdentityServiceProvider.adminEnableUser(params).promise();
}
return this._cognitoIdentityServiceProvider.adminDisableUser(params).promise();
}
从toggleUserAccess
我们传递的几个参数中可以看出,确定它们是什么然后调用相应的方法。我希望通过一个单元测试来测试这一点,该单元测试将调用authenticationService.toggleUserAccess
,传递一些参数并监视authenticationService._cognitoIdentityServiceProvider
方法以查看它们是否被调用。我是这么设置的...
let authenticationService = require('./awsAuthenticationService');
describe('toggleUserAccess', () => {
beforeEach(() => {
authenticationService._cognitoIdentityServiceProvider = {
adminDisableUser(params) {
return {
promise() {
return Promise.resolve(params);
}
};
}
};
authenticationService._cognitoIdentityServiceProvider = {
adminEnableUser(params) {
return {
promise() {
return Promise.resolve(params);
}
};
}
};
});
it('should call adminEnableUser if the type is null', () => {
authenticationService.toggleUserAccess('TheUser', null);
const spyCognito = sinon.spy(authenticationService._cognitoIdentityServiceProvider, 'adminEnableUser');
expect(spyCognito.calledOnce).to.equal(true);
});
it('should call adminDisableUser if the type is null', () => {
authenticationService.toggleUserAccess('TheUser', '0001');
const spyCognito = sinon.spy(authenticationService._cognitoIdentityServiceProvider, 'adminDisableUser');
expect(spyCognito.calledOnce).to.equal(true);
});
});
我的测试没有通过,我认为我sinon.spy
的 s 设置不正确 - 任何人都可以看到我做错了什么或请提供建议
解决方案
要存根类AWS.CognitoIdentityServiceProvider
,需要使用其prototype
关键字存根。
// add require statement for your AWS class
const spyCognito = sinon.spy(AWS.CognitoIdentityServiceProvider.prototype, 'adminDisableUser');
expect(spyCognito.calledOnce).to.equal(true);
希望能帮助到你