babel-plugin-rewire:测试私有方法

时间:2019-07-10 19:42:04

标签: javascript jestjs babeljs babel-jest

如何使用babel-plugin-rewire访问私有函数multiply并调用它进行测试?

let count = 11;

const plus = (num) => {
  return count + num;
};

export const minus = (num) => {
  return count - num;
};

const multiply = (num) => {
  return count * num;
};

export default plus;
import plus from './math.js';
import { minus, __Rewire__, __RewireAPI__ } from './math.js';

describe('math tests', () => {

  test('math.plus', () => {
    __Rewire__('count', 100);
    const result = plus(50);
    expect(result).toEqual(150); // passes
  });

  test('math.minus', () => {
    __Rewire__('count', 23);
    const result = minus(10);
    expect(result).toEqual(13); // passes
  });

  test('math.multiply', () => {
    __Rewire__('count', 100);
    const multiply = __RewireAPI__.__get__('multiply');
    console.log('multiply', multiply); // undefined
    const result = multiply(3); // error: not a function
    expect(result).toEqual(300);
  });
});

0 个答案:

没有答案