Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 973
user1261710 Avatar asked Jan 21 '17 14:01

user1261710


People also ask

Can we write unit test for JavaScript?

JavaScript Unit Testing is a method where JavaScript test code is written for a web page or web application module. It is then combined with HTML as an inline event handler and executed in the browser to test if all functionalities are working as desired. These unit tests are then organized in the test suite.

How do I run a single unit test in Visual Studio?

Run tests in Test Explorer If Test Explorer is not visible, choose Test on the Visual Studio menu, choose Windows, and then choose Test Explorer (or press Ctrl + E, T). As you run, write, and rerun your tests, the Test Explorer displays the results in a default grouping of Project, Namespace, and Class.

How do we define unit tests within a test File?

A unit test is a way of testing a unit - the smallest piece of code that can be logically isolated in a system. In most programming languages, that is a function, a subroutine, a method or property.


1 Answers

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.

like image 159
Sergeon Avatar answered Oct 17 '22 17:10

Sergeon