如何测试普通的普通javascript文件?

Jua*_*blo 4 javascript testing unit-testing

如果我有一个普通的javascript文件

// hello.js
function hello(string) {
  return 'hello ' + string;
}
Run Code Online (Sandbox Code Playgroud)

如何对该文件中的功能使用单元测试?

编辑

目前,我有两个想法(都使用nodejs):

评估+ mochajs / nodejs

使用mochajs测试框架进行测试,为此我需要使用 eval

// test file
var assert = require('assert');
var fs = require('fs');
eval.apply(this, [fs.readFileSync('./hello.js').toString()]);

describe('hello function', function() {
  it('test output', function () {
    assert.equal('hello world', hello('world'));
  });
});
Run Code Online (Sandbox Code Playgroud)

自动在nodejs模块中预转换javascript文件

在运行测试之前hello.js,请使用nodejs模块的结构自动创建一个副本,然后对该副本进行测试

// _hello.js to testing
exports.hello = function(string) {
  return 'hello ' + string;
}

// test file
var assert = require('assert');
var hello = require('./_hello.js');

describe('hello function', function() {
  it('test output', function () {
    assert.equal('hello world', hello.hello('world'));
  });
});
Run Code Online (Sandbox Code Playgroud)

在第二个选项中,我需要编写一个脚本来将javascript文件转换为nodejs模块,但是我得到了一些类似的东西,在nodejs模块中,我可以获得覆盖率度量。

Jua*_*blo 6

最后我用业力+ phantomjs +茉莉花解决了

使用业力,我可以加载javacript文件并测试文件,从而以这种方式向业力配置文件添加行

// karma.conf.js
files: [
  'hello.js',
  'hello_test.js'
],
Run Code Online (Sandbox Code Playgroud)

并以这种方式编写测试

// test_hello.js
describe('test lib', function () {
  it('test hello', function () {
    expect(hello('world')).toBe('hello world');
  });
});
Run Code Online (Sandbox Code Playgroud)

github中有一个例子

https://github.com/juanpabloaj/karma_phantomjs_jasmine


gee*_*aut 5

为此,您可以使用QUnit。

您可以像这样设置一个测试工具:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Test Suite</title>
    <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.10.1.css">
</head>
<body>
    <div id="qunit"></div>
    <div id="qunit-fixture"></div>
    <script src="https://code.jquery.com/qunit/qunit-2.10.1.js"></script>
    <script src="hello.js"></script>
    <script>
        // This can of course be in a separate file
        QUnit.test( "hello test", function( assert ) {
          assert.ok( hello('world') === "hello world", "Passed!" );
        });
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)