SpyOn individually exports ES6 features

TL; DR:

  • I use jasmine ;
  • I want to test a function aaathat called bbbfrom the same module;
  • I want to keep track of bbb, but in the end aaais called the original function bbb, not a spy;

How to aaamake a spy call?

Module:

export function aaa() {
  return bbb();
}

export function bbb() {
  return 222;
}

Test:

import * as util from 'my-module';

describe('aaa test', () => {

  let bbbSpy: Spy;

  beforeEach(() => {
    bbbSpy = spyOn(util, 'bbb');
  });

  it('should return SPYED', () => {
    bbbSpy.and.returnValue('SPYED!!');
    const result = util.aaa();
    expect(result).toEqual('SPYED!!'); // Doesn't work - still 222
  });

});

So basically this is not working. Can anybody help me?

PS I do not want to change the code of the module, because in this case I will have to change tons of code in the project. I need a generic test solution.

+4
source share
2 answers

- , , , : jest. , , .

, , , , , , .

JavaScript -. , . bbb spyOn.and.returnValue , bbb , bbb .

+2

, .

aaa . bbb . .

JavaScript, :

(() => {
  var bar = 1; // there no way to reach this variable from the outside
})();

, . ES- , CommonJS, - ( , Webpack):

exports.aaa = function aaa() {
  return exports.bbb();
}

exports.bbb = function bbb() {
  return 222;
}

, bbb * import spyOn(util, 'bbb'), . ES-, CommonJS.

, aaa bbb . , ( ES-).

+1

Source: https://habr.com/ru/post/1694645/


All Articles