Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何导入要测试的函数?_Javascript_Testing - Fatal编程技术网

Javascript 如何导入要测试的函数?

Javascript 如何导入要测试的函数?,javascript,testing,Javascript,Testing,我正在学习如何用普通Javascript测试Javascript代码,因此我将遵循一个教程。我的项目结构如下所示: Modules/File.js,File2.js(每个文件包含一个我想测试的函数) app.js(用于测试的文件,与test.js文件一起使用) index.html js(目前我把我的主代码保存在那里) html(根据教程,我使用它来运行测试) js(这是我描述测试的地方) 我希望能够从File.js和app.js中的File2.js导入函数,以便运行测试。我如何做到这一点?

我正在学习如何用普通Javascript测试Javascript代码,因此我将遵循一个教程。我的项目结构如下所示:

  • Modules/File.js,File2.js(每个文件包含一个我想测试的函数)
  • app.js(用于测试的文件,与test.js文件一起使用)
  • index.html
  • js(目前我把我的主代码保存在那里)
  • html(根据教程,我使用它来运行测试)
  • js(这是我描述测试的地方)
我希望能够从File.js和app.js中的File2.js导入函数,以便运行测试。我如何做到这一点? 另外,我正在使用es6模块导入/导出。但我想看看如何运行导入的函数进行测试。可能会使用$myapp全局变量,因为在教程中就是这样做的

test.js:

   (function () {
  'use strict';

  /**
   * test function
   * @param {string} desc
   * @param {function} fn
   */
  function it(desc, fn) {
    try {
      fn();
      console.log('\x1b[32m%s\x1b[0m', '\u2714 ' + desc);
    } catch (error) {
      console.log('\n');
      console.log('\x1b[31m%s\x1b[0m', '\u2718 ' + desc);
      console.error(error);
    }
  }

  function assert(isTrue) {
    if (!isTrue) {
      throw new Error()
    }
  }

  it('test if its a string', function () {
    assert($myapp.isValidString(2))
  })

})();
app.js文件:

(function () {
  'use strict';

  // Create a global variable and expose it to the world
  var $myapp = {};
  self.$myapp = $myapp;

  $myapp.isValidString = function (value) {
    return typeof value === 'string' || value instanceof String;
  }
  
})();

据我所知,您希望将JS函数从一个文件导入另一个文件

ES6引入了模块的功能,允许在不同文件之间导入/导出Javascript函数

下面是一个简单的例子:

// helloworld.js

export function helloWorld() {
    return 'Hello World!';
}

// main.js

import helloWorld from './helloworld.js';

console.log(helloWorld());

我已经在使用es6模块了,但我需要一些示例,说明如何在测试文件中运行函数,因为测试通过全局变量访问文件。