繁体   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