简体   繁体   中英

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. It needs to be standalone.

Here is my project:

src: myFunction.js
tests: empty for now

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:

1) Install mocha to package.json:

npm install --save-dev mocha

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) Set up the package.json test command:

{
    ...
    "scripts": {
        "test": "node_modules/mocha/bin/mocha tests/test.js"
    }
}

4) Call tests by npm test .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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