'Jest Testing - mockReset does not clear the already set values

I have a lambda which calls an interface. Am trying to mock the functions imported from the interface. In each test case, I have to mock different values. When I run all the test cases, the first mocked value does not get cleared and it is carried over to all Test cases

interface.js

  const oracledb=require("oracledb");
  module.exports = class dbLayer{
      execSql= async (sqlQuery) => {
      var result;
      var binds={};
      result = await oracledb.execute(sqlQuery,binds);
      return result
    }
  }

lambda.js

const qryInterface = require(./interface)
var db;
const handler = async (event, context) => {
  var sql= event.query
  db = new qryInterface();
  var dbResponse = await db.execSql(sql)
  return dbResponse 
}

test.js

const index = require(./lambda)
const dbMock = require(./interface)
jest.mock(./interface);

var mockResponse1 = {
  rows: [
    {
      col1 : 123
    }
  ]
}
var mockResponse2 = {
  rows: [
    {
      col1 : 456
    }
  ]
}

const firstQryResponse = async () => {
  return new Promise((resolve, reject) => {
    resolve(mockResponse1);
  });
};
const secondQryResponse = async () => {
  return new Promise((resolve, reject) => {
    resolve(mockResponse2);
  });
};

describe("1st test suite", () => {
  beforeEach(() => {
    dbMock.mockReset();
    jest.restoreAllMocks();
  });

  it("Test 1", asycn () => {
    var event={}
    event.sql=`SELECT col1 FROM TBL_A WHERE col2 = 'A'` 

    dbMock.mockImplementation(() => {
      return {
        execSql:firstQryResponse
      }
    });
    var response = await index.handler(event)
    expect(response).toEqual(mockResponse1 )
  });

  it("Test 2", asycn () => {
    var event={}
    event.sql=`SELECT col1 FROM TBL_A WHERE col2 = 'B'` 

    dbMock.mockImplementation(() => {
      return {
        execSql:secondQryResponse
      }
    });
    var response = await index.handler(event)
    expect(response).toEqual(mockResponse2 )
  });

});

Test 1 mocks the value set in firstQryResponse and Test 2 mocks secondQryResponse. But what happens is the value mocked for execSql is Not getting reset in Test 2 .i.e. firstQryResponse gets carried over to Test 2. Because of this, 2nd test fails. If i run them individually, it runs fine. I did try mockReset(), but it does not help as well.

Appreciate any help on this

Thanks Sadiq



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source