Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading