簡體   English   中英

測試AWS服務無法按預期運行時,我的Node.JS項目中的sinon.spy

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM