簡體   English   中英

關於使用 sinon 在 node js 中進行單元測試

[英]regarding unit testing in node js with sinon

class FetchTenant {

    constructor (){
        this.Config = this._getConfig();
        this.Token = this._getToken();
        this.TenantMap = new Map();
    }

    async getTenantId(Id){

        if(!this.TenantMap[Id]){
            const serviceid = await this._getInfo(Id, false);
            this.TenantMap[Id] = serviceid;
        }

        return this.TenantMap[Id];
    }

    _getConfig() {
        return get_env_from_local({ name: 'env_1' });
    }

    async _getToken() {

        const options = {
          method: 'POST',
          uri: `${this.Config.url}`,
          json: true,
          resolveWithFullResponse: false,
          transform2xxOnly: true,
          transform: body => body.access_token,
          auth: {
            username: this.Config.clientid,
            password: this.Config.clientsecret
          },
          form: {
            grant_type: 'client_credentials'
          },
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          }
        };

        return request(options)
          .catch(err => {
            logger.error('Could not get Token', err.statusCode, err.message);
            return null;
        });
    }

    async _getInfo(Id, newtoken) {
        if(newtoken){
            this.accessToken = await this._getToken();
            if(this.accessToken == null){
              logger.error(`fetching token failed`);
              return null;
            }
        }

        const options = {
          method: 'GET',
          uri: `${this.Config.url}/xyz/${Id}`,
          json: true,
          resolveWithFullResponse: false,
          transform2xxOnly: true,
          transform: body => body.tenantId,
          auth: {
            bearer: this.accessToken
          },
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          }
        };

        return request(options)
          .catch(err => {
              if(err.statusCode != 401) {
                logger.error(`Could not get tenant id`, err.statusCode, err.message);
                return null;
              }
              else {
                return this._getServiceInstanceInfo(Id, true);
              }
          });
    }

}

module.exports = FetchTenant;

這是我創建的類。

如何使用 sinon(存根和模擬)為此類編寫單元測試,我只需要測試公共函數,這里唯一的公共函數是getTenantId(Id) ,其中所有其他私有函數都有一個 http 請求,可以給出一個有效的響應或一個錯誤。

有沒有辦法通過模擬所有其他私有函數來測試公共函數。 我想預先定義將由每個私有函數返回的數據以及它們從 env 獲取並用於發送請求的主要數據。

您可以使用nock ( https://www.npmjs.com/package/nock ) 來模擬您的所有 http 調用並測試您通常會執行的公共功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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