在闭包javascript jest

时间:2019-08-13 11:53:21

标签: typescript unit-testing mocking jestjs

我正在尝试在闭包内部声明的类中模拟单个函数。

const CacheManager = (function() {
  class _CacheManager {
    constructor() {
      return this;
    }

    public async readAsPromise(topic, filter, cacheType = 'CORE') {
      if (topic.toLowerCase().equals(TOPICS[TT])) {
        const data = new Array();
        data.push(getData());
        return data;
      }
      return null;
    }
  }

  let instance;
  return {
    getInstance() {
      if (instance == null) {
        instance = new _CacheManager();
      }
      return instance;
    }
  };
})();

export { CacheManager };

我从另一个类中调用readAsPromise方法,如下所示

    class A {
     async read(param1, param2) {    
          let array = await CacheManager.getInstance().readAsPromise('topic')      
          return array[0]    
      }
    }

我从测试中调用read方法,如下所示

    A a = new A();
    a.read(param1, param2).then(....)

在上面的代码中,我想模拟方法readAsPromise。当我尝试使用genMockFromModule模拟模块时,如下所示:

const utils = jest.genMockFromModule('cache/cache_manager').CacheManager;

它只有getInstance方法,所以我不能模拟readAsPromise方法。有人可以阐明我如何在类_CacheManager中模拟readAsPromise方法。任何帮助将非常感激!预先感谢。

更新:我已经添加了控制流程的完整细节,以使我的问题更加清楚

1 个答案:

答案 0 :(得分:0)

这是解决方案:

const TOPICS = [];
const TT = '';

interface ICacheManager {
  readAsPromise(topic, filter, cacheType?): any;
  someMethod(name: string, filter): any;
}

const CacheManager = (function cacheManager() {
  class _CacheManager implements ICacheManager {
    constructor() {
      return this;
    }

    public async readAsPromise(topic, filter, cacheType = 'CORE') {
      if (topic.toLowerCase().equals(TOPICS[TT])) {
        const data = new Array();
        data.push(this.getData());
        return data;
      }
      return null;
    }

    public async someMethod(name: string, filter) {
      console.log(name, filter);
      const data = await this.readAsPromise(name, filter);
      if (data) {
        return data;
      }
      throw new Error('no data');
    }

    private getData() {
      return '';
    }
  }

  let instance;
  return {
    getInstance(): ICacheManager {
      if (instance == null) {
        instance = new _CacheManager();
      }
      return instance;
    }
  };
})();

export { CacheManager };

someMethod调用readAsPromise方法以演示如何模拟readAsPromise方法

单元测试:

import { CacheManager } from './';

const cacheManager = CacheManager.getInstance();

cacheManager.readAsPromise = jest.fn();

describe('CacheManager', () => {
  describe('#someMethod', () => {
    it('should throw error', async () => {
      (cacheManager.readAsPromise as jest.Mock<any>).mockReturnValueOnce('java');
      const actualValue = await cacheManager.someMethod('jest', 'where');
      expect(actualValue).toBe('java');
      expect(cacheManager.readAsPromise).toBeCalledWith('jest', 'where');
    });
  });
});

测试结果:

 PASS  src/mock-closure/index.spec.ts
  CacheManager
    #someMethod
      ✓ should throw error (27ms)

  console.log src/mock-closure/index.ts:25
    jest where

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.671s, estimated 2s