Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
Jest Mocking Multiple Class instances

I have class that instantiates multiple instances of the same object and I want to mock this out in jest, But I keep getting error for the second it(()=>{})('it should create second greeting')

Error: expect(received).toBe(expected) // Object.is equality

Expected: "This is the-second-greeting"

Received: "This is the-first-greeting"

Expected: "Hello and Good Evening"

Received: "Hello and Good Morning"

import {Greeting} from 'somefile/greeting'

interface FooProps {
  myProps: string
}

class Foo {
  private greeting1: Greeting;
  private greeting2: Greeting;

  constructor(bar: Bar, id: string, props: FooProps) {

    this.greeting1 = new Greeting(bar, `${id}-first-greeting`, {
      prop1: 'Hello and Good Morning',
      prop2: {
        source: ['random']
      }
    })

    this.greeting2 = new Greeting(bar, `${id}-second-greeting`, {
      prop1: 'Hello and Good Evening',
      prop2: {
        source: ['anotherRandom']
      }
    })
  }
}
import Foo from 'somefile/foo'
import {Greeting} from 'somefile/greeting'
 
jest.mock('somefile/greeting');
const FirstMock = mocked(Greeting, true);
const SecondMock = mocked(Greeting, true);

const id = 'This is';

describe('Greeting', () => {
  let bar: Bar;
  let foo: Foo;
  let random1 = ['random'];
  let random2 = ['anotherRandom'];

  const props: FooProps = {
    myProps: 'myProps'
  }
  
  beforeEach( () => {
    bar = new Bar();
    foo = new Foo(bar, id, props);
  })

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

  it('should create first greeting', () => {
    expect(random.mock.calls[0][0]).toBe(bar)
    expect(random.mock.calls[0][1]).toBe(`${id}-first-greeting`)
    expect(random.mock.calls[0][2]?.prop1).toBe('Hello and Good Morning')
    expect(random.mock.calls[0][2]?.prop2.source).toBe(random1)
  })

  it('should create second greeting', () => {
    expect(random.mock.calls[0][0]).toBe(bar)
    expect(random.mock.calls[0][1]).toBe(`${id}-second-greeting`)
    expect(random.mock.calls[0][2]?.prop1).toBe('Hello and Good Evening')
    expect(random.mock.calls[0][2]?.prop2.source).toBe(random2)
  })  

})

The first test passes, but the second one always fails. It looks like it is retaining the values of the old test. Can this be fixed?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should use jest.resetAllMocks();

clearAllMocks literally removes the state of your mock, so you are losing all the values you've setup.

Whereas resetAllMocks will return the mock to its original state.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda