如何在没有框架的情况下测试 JavaScript

Çağ*_*lar 6 javascript unit-testing intellij-idea

如何在不使用Mocha等附加框架的情况下测试 JavaScript 代码?是否可以创建单元测试用例、手动编写测试函数、测试代码等?

我尝试编写一个测试用例,但即使它们位于同一文件夹中,我也无法链接它们。

假设这是main.js文件中的一个函数

function calculate(a, b) {
    return a + b;
}
Run Code Online (Sandbox Code Playgroud)

这是testMain.js文件中的一个测试用例

function testCalculate(){
    if(calculate(1, 1) == 2)
       console.log('It Works!');
    else
       console.log('Test failed');
}

testCalculate();
Run Code Online (Sandbox Code Playgroud)

当我尝试在IntelliJ IDEA IDE中运行 testMain.js 时,出现类似以下内容的错误

“参考错误:计算未定义”

小智 8

这取决于您是要测试 Node.js 代码还是前端代码。在这两种情况下,您都必须将被测函数“暴露”给您的测试框架。

Node.js

// main.js

const obj = {};

obj.sum = (a, b) => {
  return a+b;
};

module.exports = obj; // Export 'obj' so that it is visible from your test runner

// test.js
const main = require('main.js');
const assert = require('assert');

const 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);
  }
};

it('should return the sum of two numbers', () => {
  assert.strictEqual(main.sum(5, 10), 15);
});

Run Code Online (Sandbox Code Playgroud)

当您运行时,node test.js您应该能够看到测试结果。

前端

// app.js
self.myapp = myapp; // All the methods in myapp will be exposed globally

myapp.sum = function(a, b) {
  return a + b;
}

// test.js
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(condition) {
  if (!condition) {
    throw new Error();
  }
}

it('should return a sum of two integers', function(){
  assert(myapp.sum(5, 10) === 15);
});


// test.html - This is your test runner for the front end
<html>
...
<body>
...
<script src="app.js"></script>
<script src="test.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在浏览器中打开test.html并打开浏览器控制台。您应该能够看到成功消息。

这样您就可以为 Node.js 和前端 JavaScript 代码编写测试用例,而无需使用 Mocha 或任何其他框架。


DBa*_*azs -1

如果它是 Node.js 应用程序,您只需需要其他文件并导入其他函数即可。如果项目使用Babel,您可以使用ES6 import 从其他文件导入函数。