简体   繁体   English

使用Jasmine从模块测试功能

[英]Testing a function from a module with Jasmine

I have a module "test.js" which looks like this; 我有一个看起来像这样的模块“ test.js”;

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

export function sub_main(){
 //Do something
}

I would like to test the method sub_main in Jasmine. 我想测试Jasmine中的sub_main方法。 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. 我尝试使用import语句导入sub_main()函数以在Jasmine中进行测试,但是Jasmine遵循“意外的令牌导入”,然后使用了require语句。 It now complies about export keyword in test.js module. 现在,它符合test.js模块中的export关键字。

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. 您可能希望在CommonJS模块上查找一些信息,因为这似乎是您需要使用的信息。

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. 您使用的语法实际上是ES6 import ,您的节点版本不支持。

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. 您可以在将转译的文件加载到Jasmine中之前将Babel与Jasmine一起使用,或者使用@tehbeardedone在回答中说的方式(即CommonJS)编写代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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