问题描述
我有一个 js 文件,里面有一个函数.我想为该函数编写单元测试并将测试和文件交付给某人.它需要是独立的.
I have a single js file with a function in in. I want to write unit tests for the function and deliver the tests and file to someone. It needs to be standalone.
这是我的项目:
src: myFunction.js
tests: empty for now
myFunction.js:
myFunction.js:
function HelloWord() {
return 'Hello';
}
如果有这样的测试文件就好了:
It would be great to have a test file like this:
import { func } from './myFunction.js';
describe('tests', function () {
it('returns hello', function () {
expect(func()).toEqual('Hello');
});
});
我不知道哪种单元测试框架最容易和最快地完成我需要做的事情.用户需要获取我的目录并从命令行运行测试.
I don't know which unit test framework would be the easiest and fastest to accomplish what I need to do. The user needs to get my directory and just run the tests from the command line.
推荐答案
使用 Mocha,一个非常快速的设置是:
Using Mocha, a really fast set up would be:
1) 将 mocha 安装到 package.json:
1) Install mocha to package.json:
npm install --save-dev mocha
2) 写下测试.让它成为 /tests/
下的 test.js
,例如:
2)Write down the test. Let it be test.js
under /tests/
, for example:
var myFunc = require('./myFunction');
var assert = require('assert');
describe('the function' , function(){
it('works' , function(){
assert.equal( myFunc() , 'hello');
});
});
3) 设置package.json
测试命令:
3) Set up the package.json
test command:
{
...
"scripts": {
"test": "node_modules/mocha/bin/mocha tests/test.js"
}
}
4) 通过 npm test
调用测试.
4) Call tests by npm test
.
这篇关于如何为单个 JS 文件编写单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!