0

If I have a Vue component like:

import lodash from 'lodash';

export default {

  //...data, props etc

  methods: {
    someFunction: lodash.debounce(function debouncedsomeFunction() {
      return 'test';
    }, 200)
  }

};

How would I go about testing someFunction with Mocha + Chai + Sinon?

Beau
  • 1,771
  • 1
  • 15
  • 20
  • 2
    What have you tried? There are several possible approaches depending on how much you want to mock. – Stephen Thomas Aug 13 '18 at 21:04
  • I've tried mocking, stubbing, and using fake timers, including importing lodash like `import * as lodash from 'lodash'` – Beau Aug 14 '18 at 22:03
  • So do you want to mock lodash or use it? Or more precisely, what do you want to test? Do you want to verify that your method calls lodash? Do you want to verify that the method actually debounces? Etc. If you're doing strict unit tests, then you would assume lodash is functioning and only verify that it is being invoked correctly. If you're expanding beyond unit tests, you could incorporate lodash in the test and verify debouncing. And so on. – Stephen Thomas Aug 15 '18 at 00:32
  • I want to test the heart of my function (in this case that it returns 'true'). I'm fine to assume that lodash debounce works and don't need to test it. The problem is that the unit test will complete before the function executes, and it doesn't return a promise so I can't just use `done` – Beau Aug 17 '18 at 04:29
  • See https://stackoverflow.com/a/54265129/4315740 for a debounce implementation which returns a Promise, lifesaver! – maerteijn Mar 29 '20 at 19:01

1 Answers1

0

There are several potential approaches, but it sounds like you want to mock lodash. I'll list the steps linearly for ease of presentation, but you'll probably want to distribute them appropriately within your test blocks and hooks. I'm also assuming the only call to debounce is the method in question. If not, adjust the following accordingly.

import * as Lodash from "lodash";
const debounce = sinon.stub(Lodash, "debounce").returns(() => {});
// create your component
expect(debounce.calledOnce).to.equal(true);
expect(debounce.firstCall.args[0]).to.be.a("function");
expect(debounce.firstCall.args[0]()).to.equal("test");
Lodash.debounce.restore();
Stephen Thomas
  • 13,843
  • 2
  • 32
  • 53
  • 1
    When I try your approach I get `Error: Trying to stub property 'debounce' of undefined`. If I require Lodash in my test definition Sinon doesn't complain, but I think the stub is only local to the test file and doesn't affect the Lodash being pulled into my Vue component. – Beau Aug 20 '18 at 23:01