dimanche 18 décembre 2016

How do you mock callback parameters, e.g., for chrome.storage.local.get(), in plain JavaScript (ES6)?

chrome.storage is a handy api for storing data for Chrome Extensions: http://ift.tt/1moC6v1

The get() method described there has a required callback param.

This can be used like so:

function go(storage) { // chrome.storage.local
  storage.get(MY_CONST, (result) => {
    if (!result[MY_CONST]) {
      foo();
    }
  });
}

storage is passed in as a variable so that tests can be more flexible.

However, how do you mock the value of result in tests, with plain ES6 JS? Is that possible?

For example, in a test file, you might make a fake storage class and pass that in when you call go():

class FakeStorage {
  constructor() {
    this.data = {};
  }
  set(keyValuePair) {
    this.data = keyValuePair;
  }
  get(key, callback) {
    callback(); // how do you force a parameter in the callback?
  }
}

I can think of a way to test by spying on chrome.storage.local, but I would like to know if I can mock with plain JS instead, because then, the whole point of abstracting storage to be a parameter for go() is pointless. (Moreover, it's better to mock if you can, since it just forces you to test the core functionality; spying can become verbose.)

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire