简体   繁体   中英

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;

this is the class that i have created.

how to write a unit test for this class using sinon (stub and mock),i have to test only the public functions and the only public function here is getTenantId(Id) where in all the other private functions have a http request which can give either a valid response or an error.

is there any way to test the public function by mocking all the other private functions. i want to pre-define the data which will be returned by each private function and the primary data they fetch from env and use to send the request.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM