requireActual不返回原始类定义

时间:2020-05-07 10:00:08

标签: unit-testing mocking jestjs

免责声明:一直在玩Jest嘲讽游戏,但还是个新手,所以可能完全是错误的想法。

对于大多数测试,我不会为另一个测试类的测试套件保留多余的实现细节,但是对于某些测试,我需要访问原始类,包括正在验证的定义类型。示例代码如下:

MyClass.js

export default class MyClass {
  constructor(p1) {
    if (p1 === undefined) {
      throw new Error('Missing arg');
    }
    ...
  }

  isPositive(val) {
    return val > 0;
  }
}

Collection.js

import MyClass from './MyClass';

export default class Collection {
  addItem(item) {
    if (!(item instanceof MyClass)) {
      throw new Error('Value is not instance of MyClass');
    }
    ...
  }
}

mock.test.js

import Collection from './Collection';
import MyClass from './MyClass';

jest.mock('./MyClass');

describe('Mocks', () => {
  beforeEach(() => {
    MyClass.mockClear();
  });

  it('should not throw on addition of valid object', () => {
    const inst = new Collection();
    const mock = new MyClass(); // no parameter needed
    expect(() => {
      console.log(mock.isPositive(7)); // undefined
      inst.addItem(mock);
    }).not.toThrow();
  });

  it('should be fine with original', () => {
    jest.unmock('./MyClass');
    jest.resetModules();
    const MyClassOrig = jest.requireActual('./MyClass').default;
    const inst = new Collection();
    const orig = new MyClassOrig(1); // have to include parameter
    expect(() => {
      console.log(orig.isPositive(7)); // true
      inst.addItem(orig);
    }).not.toThrow();
  });
});

第二个测试会抛出来自 Collection.js 的“值不是MyClass实例”,即使MyClassOrig是原始实现,调用isPositive()时正确的返回值也证明了这一点当调用没有参数的构造函数时抛出错误“ Missing arg”时,模拟版本不是这种情况。

是否可以重置模拟模块,因为根本没有模拟发生?

我还尝试了仅在需要时(甚至我的情况恰好相反)使用US jest.doMock()时进行模拟的另一种方法,其结果为“值不是MyClass的实例”。

相似的问题:Using requireActual isn't requiring the actual version of module, in a Jest test

0 个答案:

没有答案