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

时间:2019-10-04 19:25:03

标签: 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 IDE上运行testMain.js时,出现类似于

的错误
  

“ ReferenceError:未定义计算”

4 个答案:

答案 0 :(得分:0)

如果它是NodeJS应用程序,则只需要另一个文件并导入另一个功能。如果项目使用Babel,则可以使用ES6 import从其他文件导入功能。

答案 1 :(得分:0)

要使代码正常工作,您的testMain.js文件需要以某种方式导入main.js代码。

在main.js文件中:

function calculate(a, b) {
    return a+b;
}

module.exports.calculate = calculate

在testMain.js文件中,导入main.js:

var main = require('main.js')

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

注意:我知道这不一定显示出良好的编码风格,只是为了演示原始问题,而只需对原始摘要进行最小的改动即可。

也就是说,通常不值得重新发明轮子并建立自己的测试框架。您能否阐明为什么要避免使用现有框架的原因?如果您正在寻找简单性,也许可以使用jstinytest之类的技巧。

答案 2 :(得分:0)

这取决于您是否要测试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 sum of two numbers', ()=>{
  assert.strictEqual(main.sum(5, 10), 15);
});

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

前端

// app.js
self.myapp = myapp; // All the methods on 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,然后打开浏览器控制台。您应该能够看到成功消息。

这样,您可以在不使用Mocha或任何其他框架的情况下为node.js和前端javascript代码编写测试用例。

答案 3 :(得分:-2)

我也被同样的问题困扰了一段时间。问题是如何在没有测试框架的情况下测试您的 JavaScript 代码,因为测试框架的工作带来了很多问题,而且大多数时候它们都会妨碍工作。


  • 答案是在没有测试框架的情况下使用断言库。例如,您可以使用没有 mocha 框架的 chai 断言库

你可以简单地安装 chai npm install chai
之后你就可以使用它了:

var should = require('chai').should() 

const log = console.log;

//log(should);

//const letters = "abcdef";

const letters = 555;


letters.should.be.a('string');
相关问题