Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub exported function in ES6?

I have file foo.js:

export function bar (m) {   console.log(m); } 

And another file that uses foo.js, cap.js:

import { bar } from 'foo';  export default m => {   // Some logic that I need to test   bar(m); } 

I have test.js:

import cap from 'cap'  describe('cap', () => {   it('should bar', () => {       cap('some');   }); }); 

Somehow I need override implementation of bar(m) in test. Is there any way to do this?

P.S. I use babel, webpack and mocha.

like image 829
Mike Chaliy Avatar asked Jan 03 '16 10:01

Mike Chaliy


People also ask

Can I export function in JavaScript?

You can export as many functions as needed as long as you remember that there can be only one default export. The default export in JavaScript is used to export a single/fallback value from a module. With a default export, you do not need to specify a name for the exported function. The filename is used by default.

Can you export functions?

Use named exports to export a function in JavaScript, e.g. export function sum() {} . The exported function can be imported by using a named import as import {sum} from './another-file. js' . You can use as many named exports as necessary in a file.

What is import and export in ES6?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.


1 Answers

Ouch.. I found solution, so I use sinon to stub and import * as foo from 'foo' to get object with all exported functions so I can stub them.

import sinon from 'sinon'; import cap from 'cap'; import * as foo from 'foo';  sinon.stub(foo, 'bar', m => {     console.log('confirm', m); });  describe('cap', () => {   it('should bar', () => {     cap('some');   }); }); 
like image 105
Mike Chaliy Avatar answered Oct 10 '22 04:10

Mike Chaliy