Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the convention for JavaScript test files?

I've seen a few files called *.test.js, *-test.js, *.spec.js, etc.

Is there an actual convention how to name JavaScript test files? Or is this dependent on the framework I use?

like image 530
tschaka1904 Avatar asked Apr 03 '18 14:04

tschaka1904


1 Answers

After using several test frameworks, I feel the below is better:

For test file names, use as below:

  1. /test/*.test.js - preferred, no need to explain.
  2. /test/*.spec.js - OK, but new joinees always ask me - why?. A spec here means requirement specification.
  3. /test/*.test.txt - preferred, if test cases are in a text file. A set of line(s) is a test case (see below).

For example:

  • a.js is the main JavaScript file that should be tested
  • /test/a.test.js is the test file that tests above a.js. Note that /test/ is a test folder.

You may find *.test.txt new, so adding more details.

The format of one test case being three lines, can be in the below format in *.test.txt:

  • inputParam1 - may be the first parameter of a critical function which needs many tests
  • inputParam2 - may be second parameter of a critical function which needs many tests
  • expected
  • inputParam1
  • inputParam2
  • expected
  • ...

So, every three lines make one test case.

You may add the function name line like below, once in a while, which tests different function:

  • -func:someMethod1
  • ... (above input/expected lines)
  • -func:someMethod2
  • ... (above input/expected lines)

To execute a function name, or create a new object to a class, you can use eval(className), someMethod1[inputParam], etc. Though eval is not recommended, I use it as it is test framework which is not the production file. You will better ways than eval though if that is a concern.

After using several test frameworks, found this text file testing, by far most convenient for some special cases. (No need to format in JavaScript, JSON, etc.)

If you need, you may ignore that start with #, or //, or all blank lines.

So, I wrote my own framework that works this way.

  • If you know a test framework that can read above format for *.test.txt, do comment below.

  • Ping me if you need my code, will share via GitHub.

like image 199
Manohar Reddy Poreddy Avatar answered Sep 28 '22 19:09

Manohar Reddy Poreddy