[英]How do I write unit tests for a single JS file?
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. 我有一个带功能的js文件。我想为该功能编写单元测试,并将测试和文件交付给某人。 It needs to be standalone. 它必须是独立的。
Here is my project: 这是我的项目:
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. 用户需要获取我的目录,然后仅从命令行运行测试。
Using Mocha, a really fast set up would be: 使用Mocha,一个真正快速的设置将是:
1) Install mocha to package.json: 1)将mocha安装到package.json:
npm install --save-dev mocha
2)Write down the test. 2)写下测试内容。 Let it be test.js
under /tests/
, for example: 使其成为/tests/
下的test.js
,例如:
var myFunc = require('./myFunction');
var assert = require('assert');
describe('the function' , function(){
it('works' , function(){
assert.equal( myFunc() , 'hello');
});
});
3) Set up the package.json
test command: 3)设置package.json
测试命令:
{
...
"scripts": {
"test": "node_modules/mocha/bin/mocha tests/test.js"
}
}
4) Call tests by npm test
. 4)通过npm test
调用测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.