[英]sinon.spy in my Node.JS project when testing an AWS service not working as expected
在我的Node.JS项目(一个Angular 5项目的后端)中,我创建了一个处理AWS Authentication ...的服务,我将其称为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
类进行AWS.CognitoIdentityServiceProvider
,需要对其prototype
关键字进行存根。
// add require statement for your AWS class
const spyCognito = sinon.spy(AWS.CognitoIdentityServiceProvider.prototype, 'adminDisableUser');
expect(spyCognito.calledOnce).to.equal(true);
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.