如何在jest中的测试之间恢复模拟实现?

时间:2018-06-18 14:46:50

标签: javascript unit-testing jestjs

我正在尝试在同一个文件中为不同的函数创建两个测试。

我有func1在其中调用func2,因此我正在监视func2并嘲笑其实施以测试func1,并在第一个结束时测试我正在恢复模拟。

问题是第二次测试失败,因为func2实现仍然被模拟。

为什么模拟还原不恢复?

describe('myClass.func1', () => {
  it('returns true', async () => {
    const func2spy = jest.spyOn(myClass, 'func2').mockImplementation(() => true);
    await expect(func1()).toBe(true);
    func2spy.mockRestore();
  })
});

describe('myClass.func2', () => {
  it('returns false if argument is 0', () => {
    expect(func2(0)).toBe(false);
  })
});

1 个答案:

答案 0 :(得分:0)

这是一个适合我的演示作品:

index.ts

export class MyClass {
  constructor() {}

  public async func1() {
    return this.func2();
  }
  public func2(int?: number) {
    return false;
  }
}

index.spec.ts

import { MyClass } from './';

const myClass = new MyClass();

describe('MyClass.func1', () => {
  it('returns true', async () => {
    const func2Spy = jest.spyOn(myClass, 'func2').mockImplementation(() => true);
    const actualValue = await myClass.func1();
    expect(actualValue).toBeTruthy();
    func2Spy.mockRestore();
  });
});

describe('myClass.func2', () => {
  it('returns false if argument is 0', () => {
    expect(myClass.func2(0)).toBe(false);
  });
});

单元测试结果:

 PASS  src/stackoverflow/50912106/index.spec.ts
  MyClass.func1
    ✓ returns true (7ms)
  myClass.func2
    ✓ returns false if argument is 0 (1ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        4.939s, estimated 5s
相关问题