How to stub imported Ember functions?

The old syntax looked like this:

import Ember from 'ember';
...
Ember.Logger.warn(...);

which was easy to stub using sinon. However, the new syntax:

import { warn } from '@ember/debug';
...
warn(...);

is not so easy to mock. How do I stub in this case?


I tried this in my test file:

import * as EmberDebug from '@ember/debug';
...
sinon.stub(EmberDebug, 'warn');

but then I get this error:

Error: Could not find module `@ember/debug` imported from `my-project/tests/unit/pods/components/my-component/component-test`

Yeah, ES modules (in the Javascript language itself) are designed to prevent this kind of thing.

There is registerWarnHandler though.

registerWarnHandler worked, but I can’t imagine all other cases have a similar solution…

For the record, another thing future-googlers can try is

// component.js
import { warn } from '@ember/debug';
...
// component.js
Ember.Component.create({
  warn,
  ...
  this.get('warn')('Could not foo the bar');
});
// component-test.js
const subject = this.subject({
  warn: sinon.stub(),
});

Unfortunately, for warn specifically, this causes a test-loader crash. But maybe it will work for other cases.

1 Like

I did this earlier today and it worked fine.

import { run } from '@ember/runloop';
const { spy } = sinon;
...
const debounce = spy(run, 'debounce');

How is your case different?

That is a nice trick to stub the individual methods. I think it is the recommended way to do that. I have one example that I think highlights the problem @BlueRaja was describing. Some things only export functions, like utilities.

I have a utility in my app that I want to stub. A route imports the utility and calls it on the model hook’s resolved data. I’d rather not have my route test also assert behavior from that utility.

I did find that you can stub a given utility with stubbedFunc = sandbox.stub(require(my-app/utils/some-util'), 'default'); That relies upon the dependency loading implementation though, and so would be prone to obscure failures in the future. Because of that, I do not recommend using this in an app.

A little bit late for the party, but stumbled upon this today. You may use ember-sinon-qunit for this goal.
This thread shows you can do:

import * as fetch from 'fetch'
...
sinon.stub(fetch, 'default')
1 Like