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

标签 javascript unit-testing intellij-idea

如何在不使用额外框架(如 Mocha)的情况下测试 JavaScript 代码?是否可以创建单元测试用例、手动编写测试函数、测试代码等?
我试图写一个测试用例,但即使它们在同一个文件夹中,我也无法链接它们。
假设这是 中的一个函数main.js 文件

function calculate(a, b) {
    return a + b;
}
这是 中的一个测试用例testMain.js 文件
function testCalculate(){
    if(calculate(1, 1) == 2)
       console.log('It Works!');
    else
       console.log('Test failed');
}

testCalculate();
当我尝试在 IntelliJ IDEA 中运行 testMain.js 时IDE 我收到类似的错误

"ReferenceError: calculate is not defined"

最佳答案

这取决于您是在尝试测试 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);
});

当你运行 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>
打开test.html在浏览器中打开浏览器控制台。您应该能够看到成功消息。
这样您就可以为 Node.js 和前端 JavaScript 代码编写测试用例,而无需使用 Mocha 或任何其他框架。

关于javascript - 如何在没有框架的情况下测试 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58242163/

相关文章:

javascript - Backbone.js:集合的 "change"事件未触发

javascript - ASP.NET AJAX UpdatePanel - 在 InitializeRequest 中取消回发不会设置回重新启用

java - AssertJ 断言原因消息

java - IntelliJ IDEA 13 社区版 - EJB Facet 缺失

java - Intellij IDEA 是如何管理插件依赖的?

javascript - 使用 JavaScript 解压缩文件

javascript - jQuery 获取文本区域光标/插入符号 X、Y 位置并在下方显示一个 DIV

调试构建类型的 Android 单元测试失败

c# - 是否可以从 Protractor 测试中调用 C# 代码?

java - IntelliJ IDEA 无法识别 forEach 调用中的方法递归