mercredi 3 juillet 2019

Jest mock or spy to change parameter value when original function is called

Let's say I have a write function that takes a filename:

class Writer {
  static write(filename){// writes to filesystem}
}

In the function under test, it calls Writer.write with a hard-coded filename:

const writeStuff = () => {Writer.write('./fileA');};

Then in my Jest test, I want to force writeStuff to use a different filename.

I have tried something like this, and I get an infinite loop in the call stack (not surprised - don't need an explanation):

const original_writer = (filename) => { return Writer.write(filename); };

jest.spyOn(Writer, 'write').mockImplementation((filename) => {
      original_writer('./fileB');
    });

I'm sure I'm missing something simple, but I can't figure out how to make this work. I've already searched all Stack Overflow posts and blogs regarding mocking, and found nothing that resembles this scenario.

How can I call the same function implementation with different arguments, but only under test, in this scenario? Don't reply with use DI (dependency injection), please. It would be trivial to change the writeStuff function to accept the filename as a parameter as well.

Aucun commentaire:

Enregistrer un commentaire