简体   繁体   English

开玩笑模拟多个类实例

[英]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错误:expect(received).toBe(expected) // Object.is 相等

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?这可以解决吗?

You should use jest.resetAllMocks();你应该使用jest.resetAllMocks();

clearAllMocks literally removes the state of your mock, so you are losing all the values you've setup. clearAllMocks从字面上删除了您的模拟状态,因此您将丢失您设置的所有值。

Whereas resetAllMocks will return the mock to its original state.resetAllMocks会将模拟返回到其原始状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM