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

时间:2017-03-05 22:02:48

标签: javascript unit-testing testing

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

t = str.maketrans(dict.fromkeys(punc_list, " "))
new_s = s.lower().translate(t)

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

修改

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

eval + mochajs / nodejs

使用mochajs测试框架进行测试,为此我需要使用// hello.js function hello(string) { return 'hello ' + string; }

eval

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

在运行测试之前,自动创建具有nodejs模块结构的// 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')); }); }); 副本,并对副本运行测试

hello.js

在第二个选项中,我需要创建一个脚本来将javascript文件转换为nodejs模块,但我得到一些东西,比如,在nodejs模块中我可以得到覆盖度量。

4 个答案:

答案 0 :(得分:5)

最后我用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

答案 1 :(得分:2)

为此,您可以使用QUnit

您可以设置如下测试工具:

<!doctype html>
<html>
<head>
  <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.2.0.css">
</head>
<body>
  <script src=""https://code.jquery.com/qunit/qunit-2.2.0.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>

答案 2 :(得分:0)

使用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();

答案 3 :(得分:-1)

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

enter image description here