简体   繁体   中英

Testing a function from a module with Jasmine

I have a module "test.js" which looks like this;

export default function main(){
   sub_main();
}

export function sub_main(){
 //Do something
}

I would like to test the method sub_main in Jasmine. I have tried to import sub_main() function to test in Jasmine using import statement but Jasmine complies "Unexpected token import" then I used the require statement. It now complies about export keyword in test.js module.

This should help get you on the right path. You may want to look up some info on CommonJS modules as it looks like that is what you need to be using.

module.exports = {
    main: function() {
        this.sub_main();
    },

    sub_main: function() {
        return 'It Works!';
    }
}

And a working test example:

it('should work', function() {
  const sub_main = require('./path/to/myModule').sub_main;
  const itWorks = sub_main();

  expect(itWorks).toEqual('It Works!');
});

The syntax you're using is actually ES6 imports , which is not supported by your node version.

You'd either either to use Babel with Jasmine before loading transpiled files into Jasmine, or write your code using the way that @tehbeardedone said on his answer, which is CommonJS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM