繁体   English   中英

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

[英]How can I test a normal plain javascript file?

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

// hello.js
function hello(string) {
  return 'hello ' + string;
}

如何对该文件中的函数使用单元测试?

编辑

目前我有两个想法(都使用 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'));
  });
});

自动预转换 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'));
  });
});

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

最后我用 karma + phantomjs + jasmine 解决了

使用 karma 我可以加载 javacript 文件和测试文件,以这种方式向 karma 配置文件添加行

// karma.conf.js
files: [
  'hello.js',
  'hello_test.js'
],

并以这种方式编写测试

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

github 中提供的示例

https://github.com/juanpabloaj/karma_phantomjs_jasmine

为此,您可以使用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>

使用PreemJS ,有利于 API\\Unit javascript 测试

    "use strict";

    let Preem = require('preem');

    let preem = new Preem();

    preem.testModule("Test hello function", function(beforeEach, checkIf) {

        function hello(string) {
           return 'hello ' + string;
        }

        let str = hello('world');

        checkIf(str).isEqualTo('hello world', "strings are equal", "strings aren't equal");

    }
    preem.start();

1) 转到https://jsfiddle.net/ , 2) 在 Javascript 块中输入您的代码。 3) 在 Windows 上按 F12 打开 Chrome 控制台窗口。 4)点击左上角的运行。 希望这可以帮助。

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM