如何在不使用额外框架(如 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/