DEV Community

sagarMehta1907
sagarMehta1907

Posted on

How to cover code coverage for IF/ELSE condition with the node using the JEST unit test

We are trying to cover code coverage for the node js function but for the if-else condition, we can't get code coverage, so any idea about that how to cover code coverage for the if-else condition.

Please refer screenshot for sonar code coverage.

exports.findMyCompanies = function(user) {return new Promise(function(resolve, reject) {

let query = `SELECT id,name,description,TYPE,website,org_type,linkedin_profile,logo_url,entity_type,(SELECT  count(*) from pages_access as pa where pa.shared_with_org_id = ? and pa.org_id = org.id) as privileges_count FROM organization org WHERE active=true  and org.id in (SELECT  distinct company_org_id org_id from company_advisor where advisor_org_id=?)`;

dbClient.getConnection().then(function(connection) {
  connection.beginTransaction(function(error_connection, resultData) {
    if (error_connection) {
      dbClient.END_TRANSACTION(connection, "ROLLBACK");
      reject(new Error(error_connection));
      return;
    }

    let orgGetQuery = "select * from `organization` where id=?";
    connection.query(orgGetQuery, [user.org_id], function(err, results) {
      if (err) {
        dbClient.END_TRANSACTION(connection, "ROLLBACK");
        reject(new Error(err));
        return;
      }

      if (
        results.length > 0 &&
        (results[0].type == SYSTEM_ADMIN_ORG ||
          results[0].type == "capitalprovider")
      ) {
        query = `
            SELECT id,
                 name,
                 description,
                 TYPE,
                 website,
                 org_type,
                 linkedin_profile,
                 logo_url,
                 entity_type
            FROM organization org where type='company' and active=true `;
      } else if (results.length < 1) {
        dbClient.END_TRANSACTION(connection, "ROLLBACK");
        reject(new Error("Unknown organization of user"));
        return;
      }

      connection.query(query, [user.org_id, user.org_id], function(
        error_getting_shared_companies,
        results_getting_shared_companies
      ) {
        if (error_getting_shared_companies) {
          dbClient.END_TRANSACTION(connection, "ROLLBACK");
          reject(new Error(error_getting_shared_companies));
          return;
        }

        dbClient.END_TRANSACTION(connection, "COMMIT");
        resolve(results_getting_shared_companies);
      });
    });
  });
});});};
Enter fullscreen mode Exit fullscreen mode

Jest Unit test case for node js function

it("The function find my company", async () => {

user = { org_id: "92e1f7fe-93fc-4e51-a86e-8c4962dcef49" };
await advisor
  .findMyCompanies(user)
  .then(companyData => {
    expect(companyData).not.toBeNull();
  })
  .catch(err => {
    console.log("Error:- ", err);
  });  
Enter fullscreen mode Exit fullscreen mode

});

Top comments (0)