Search code examples
reactjsunit-testingjestjsmockingts-jest

jest.resetAllMocks not clearing the previous describes's mock. and spyOn not working inside the describe


i'm writing unit test cases for the utils files which is using external libraries like near-api-js Ethersjs. now the situation is that i have multiple utils files for which i have written separated unit test cases files and i want to run all these files from a single source. so for that i made an index file and imported all the other main describes into it and now running only the index file.

But the problem is some mock which were made to the previous files are not clearing up at the end of the file and other files are consuming these packages but their original version, not mocked version.

jest.clearAllMocks();
jest.resetAllMocks();

both the commands not working as we want to. attaching the code below

describe("utils files test cases", () => {
    beforeAll(() => {
        jest.spyOn(CachedService, "getHashedPassword").mockReturnValue("0x4cc447191e19f3d492b3e6dc74172a6ea597c68880b62674e21af15b90022e35");
    });


    describe("utilActivity", () => {
        StaticStore.dispatch(setAppSliceState());
        StaticStore.dispatch(setNewWalletState());
        jest.clearAllMocks();
        jest.resetAllMocks();
        utilActivity();
    });

    describe("utilNotifications", () => {
        StaticStore.dispatch(setAppSliceState());
        StaticStore.dispatch(setNewWalletState());
        jest.clearAllMocks();
        jest.resetAllMocks();
        generateNotificationTest();
    });

    describe("utilNear", () => {
        StaticStore.dispatch(setAppSliceState());
        StaticStore.dispatch(setNewWalletState());
        jest.clearAllMocks();
        jest.resetAllMocks();
        utilNearTest();
    });

})
jest.mock("near-api-js", () => {
  const originalModule = jest.requireActual("near-api-js");
  return {
    __esModule: true,
    ...originalModule,

    KeyPair: {
      fromString: jest
        .fn()
        .mockReturnValue(
          "5eeb5878647747efa8d53129c85f0cfc60370049e40fc9dc2f331d51db2f58d1"
        ),
    },
    providers: {
      JsonRpcProvider: jest.fn().mockReturnValue({
        query: jest.fn().mockReturnValue("access ket"),
        block: jest.fn().mockReturnValue({
          header: {
            hash: "0x11111111111111",
          },
        }),
      }),
    },
    transactions: {
      createTransaction: jest.fn().mockImplementation(() => "neartx"),
      signTransaction: jest
        .fn()
        .mockReturnValue([
          "",
          "5eeb5878647747efa8d53129c85f0cfc60370049e40fc9dc2f331d51db2f58d1",
        ]),
      functionCall: jest.fn(),
    },
    utils: {
      PublicKey: {
        from: jest.fn(),
      },
      serialize: {
        base_decode: jest.fn(),
      },
    },
  };
});

describe("utils.near", () => {
  beforeEach(() => {
    jest
      .spyOn(CachedService, "getHashedPassword")
      .mockReturnValue(
        "0x4cc447191e19f3d492b3e6dc74172a6ea597c68880b62674e21af15b90022e35"
      );
  });

  describe("validateAccessKey", () => {
    it("should return accessKey if permission is 'FullAccess'", () => {
      expect(utilNear.validateAccessKey(transaction, accessKey)).toBe(
        accessKey
      );
    });
    it("should return null if transaction receiver_id is different from the accessKey's receiver_id", () => {
      expect(utilNear.validateAccessKey(transaction, accessKey2)).toBeNull();
    });

    it("should return false if transaction action type is not FunctionCall", () => {
      expect(utilNear.validateAccessKey(transaction3, accessKey3)).toBeFalsy();
    });

    it("should return false if transaction methodName is included in the accessKey's method_names", () => {
      expect(utilNear.validateAccessKey(transaction4, accessKey4)).toBeFalsy();
    });

    it("should return false if transaction methodName is not  included in the accessKey's method_names", () => {
      expect(utilNear.validateAccessKey(transaction5, accessKey5)).toBeTruthy();
    });
  });
})

i tried clearing mocking afterEach and afterAll within the test file and outside the test file. i want a fresh state for after the start of every file.

jest.clearAllMocks();
jest.resetAllMocks();

Solution

  • I think what's going wrong for you here is that your spies aren't being restored, so as well as calling:

    jest.clearAllMocks();
    jest.resetAllMocks();
    

    You should also call:

    jest.restoreAllMocks()
    

    Infuriating and confusing - I know. More info here: Difference between resetAllMocks, resetModules, resetModuleRegistry, restoreAllMocks in Jest