I am currently working on a project where I have a class that creates multiple instances of the same object. I am trying to mock this behavior in jest, but I keep encountering an error specifically for the second instance creation test.
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[1][0]).toBe(bar)
expect(random.mock.calls[1][1]).toBe(`${id}-second-greeting`)
expect(random.mock.calls[1][2]?.prop1).toBe('Hello and Good Evening')
expect(random.mock.calls[1][2]?.prop2.source).toBe(random2)
})
})
Although the first test passes successfully, there seems to be an issue with retaining old values when running the second test. Any ideas on how to resolve this?