If you want to create a Javascript/Node coding tutorial, you have to use the @learnpack/node
plugin in order to compile and test your exercises. Go to Compiler Plugins to see how to install the plugin.
In addition, the main file should be named app.js
(or you can set the name on the learn.json), and the file for the tests, should be named tests.js
(you can also set the name on the learn.json).
For testing, you should install Jest with the version "24.8.0". You can install it by running the following command: npm install jest@24.8.0 -g
If you are not familiar with Jest, here are the most common tests that you will use when testing a Javascript exercise tutorial:
1//tests.js 2 3// rewirte library is used to avoid using import/export statements on the student code 4const rewire = require('rewire'); 5 6test('The variable "name" should exist', () => { 7 const file = rewire("./app.js"); 8 const name = file.__get__("name"); 9 expect(name).not.toBe(undefined); 10})
1 2// tests.js 3 4const rewire = require('rewire'); 5 6test('The variable "name" should have "James" as its value', () => { 7 const file = rewire("./app.js"); 8 const name = file.__get__("name"); 9 expect(name).toBe("James"); 10})
1// tests.js 2 3const rewire = require('rewire'); 4 5test('The function "sum" should exist', () => { 6 const file = rewire("./app.js"); 7 const sum = file.__get__("sum"); 8 expect(sum).not.toBe(undefined); 9})
1// tests.js 2 3const rewire = require('rewire'); 4 5test('The function "sum" should return the sum of two numbers', () => { 6 const file = rewire("./app.js"); 7 const sum = file.__get__("sum"); 8 expect(sum(4, 8)).toBe(12); 9})
1// tests.js 2 3const fs = require('fs'); 4const path = require('path'); 5const rewire = require('rewire'); 6 7test('You have to use Math.random() function', () => { 8 const file = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); 9 const regex = /Math\s*\.\s*random/gm 10 expect(regex.test(file.toString())).toBeTruthy(); 11})
1// tests.js 2 3const rewire = require('rewire'); 4let buffer = ""; 5global.console.log = console.log = jest.fn((text) => buffer += text + "\n"); 6 7test('You have to call console.log() with "Hello World!" as value', () => { 8 const file = rewire("./app.js"); 9 expect(buffer.includes("Hello World!\n")).toBe(true); 10})
1// tests.js 2 3const rewire = require('rewire'); 4global.console.log = console.log = jest.fn(text => null); 5 6test('You have to call console.log() with 50 as value', () => { 7 const file = rewire("./app.js"); 8 expect(console.log).toHaveBeenCalledWith(50); 9})
1// tests.js 2 3const rewire = require('rewire'); 4global.console.log = console.log = jest.fn(text => null); 5 6test('You have to call console.log() twice', () => { 7 const file = rewire("./app.js"); 8 expect(console.log.mock.calls.length).toBe(2); 9})
The following links are javascript coding tutorials: