Search code examples
javascripttypescriptjestjsspyon

jest.spyOn looks like its sharing context across multiple tests (in the same describe)


When I just run my individual test it works. When I run the whole file I get this error. enter image description here

Let's say I have an entity called Group, Group has properties and methods. I'm trying to verify that these methods are called given the conditions scenario.

My guess is that im using jest.spyOn in the wrong way. Group.prototype works, but when I have multiple tests running, looks like if test A executes method X, test B already counts that method X has been called.

enter image description here

it('should update only perm and name', async () => {
  const spyOnPerm = jest.spyOn(Group.prototype, 'changePermissions');
  const spyOnName = jest.spyOn(Group.prototype, 'changeName');
  const spyOnIsDpt = jest.spyOn(Group.prototype, 'changeIsDepartment');
  const command = new ChangeGroupPermissionCommand({
    group,
    propsToChange: {
      permissions: [Permission.createFromBitmap('@iam.11111111')],
      name: 'new name' + Math.random(),
    },
  });
  await context.run(author, async () => {
     await handler.execute(command);
     expect(spyOnPerm).toBeCalledTimes(1);
     expect(spyOnName).toBeCalledTimes(1);
     expect(spyOnIsDpt).not.toBeCalled();
  });
});

it('should update only department status', async () => {
  const spyOnPermission = jest.spyOn(Group.prototype, 'changePermissions');
  const spyOnName = jest.spyOn(Group.prototype, 'changeName');
  const spyOnIsDpt = jest.spyOn(Group.prototype, 'changeIsDepartment');

  const command = new ChangeGroupPermissionCommand({
    group,
    propsToChange: {
      isDepartment: true,
    },
  });
  await context.run(author, async () => {
    await handler.execute(command);
    expect(spyOnPermission).not.toBeCalled();
    expect(spyOnName).not.toBeCalled();
    expect(spyOnIsDpt).toBeCalled();
  });
});

Solution

  • You can use something like that :

    afterEach(() => {    
      jest.clearAllMocks();
    });