关于使用sinon在node js中进行单元测试

时间:2020-01-17 09:12:48

标签: node.js mocking sinon stub

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可以给出有效响应或错误的请求。

有没有办法通过模拟所有其他私有函数来测试公共函数。我想预定义将由每个私有函数返回的数据以及它们从环境中获取并用于发送请求的主要数据。

1 个答案:

答案 0 :(得分:0)

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