【问题标题】:regarding unit testing in node js with sinon关于在 node js 中使用 sinon 进行单元测试
【发布时间】:2020-05-04 03:48:28
【问题描述】:
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 获取并用于发送请求的主要数据。

【问题讨论】:

    标签: node.js mocking sinon stub


    【解决方案1】:

    您可以使用nock (https://www.npmjs.com/package/nock) 来模拟您的所有 http 调用并测试您通常会执行的公共函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 2021-03-15
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2019-02-14
      相关资源
      最近更新 更多