【问题标题】:how can I spy on a function with jest我怎样才能用玩笑来监视一个函数
【发布时间】:2017-12-16 04:39:12
【问题描述】:

我有一个调用另一个函数的函数

const getArtist = (id) => {
// builds params for other function
return otherFuntion(params);
}

我想验证当我调用getArtist(someValue) 时,otherFunction 会被正确的参数调用。 我怎样才能用玩笑来做到这一点?

describe('getArtist function', () => {
    it('should call otherFunction with the right params', () => {
        // how can I get a handle on the mock of otherFunction to see
        // if it was called correctly ?
    });
});

【问题讨论】:

    标签: javascript reactjs jasmine jestjs


    【解决方案1】:

    如果导入的函数是公共函数,您可以在编译时使用proxyquire 模拟它。如果它是一个私有函数,那么你肯定不想模拟它。

    您应该只测试otherFuntion 的返回值。

    【讨论】:

      【解决方案2】:

      所以你真的在调用函数 otherFuntion(params) 所以我宁愿检查你的 getArtist 函数的返回是否与 otherFunction 给出相同的结果strong> 使用正确的参数调用。

      describe('getArtist function', () => {
        it('should call otherFunction with the right params', () => {
          expect(getArtist(id)).toBe(otherFunction(params));
        });
      });
      

      或者创建特殊函数来生成参数并单独测试。喜欢 prepareArtistParams 并在里面使用它:

      const getArtist = (id) => {
        const params = prepareArtistParams(id);
        return otherFuntion(params);
      }
      
      describe('otherFuntion function', () => {
        it('should create right params', () => {
          expect(prepareArtistParams(id)).toBe(params);
        });
      });
      

      【讨论】:

        猜你喜欢
        • 2019-05-27
        • 2022-12-09
        • 1970-01-01
        • 2019-07-09
        • 2017-11-23
        • 2020-09-08
        • 2017-07-14
        • 2015-10-07
        • 1970-01-01
        相关资源
        最近更新 更多