How to stub imported Ember functions?

#1

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`
0 Likes

#2

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

There is registerWarnHandler though.

0 Likes

#3

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

#4

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?

0 Likes