Use jest to compare content of two files - javascript

I'm trying to switch from Mocha and Chai to Jest. In my current setup I'm also using chai-files to compare the contents of two files:
import chai, { expect } from 'chai';
import chaiFiles, { file } from 'chai-files';
import fs from 'fs-extra';
import { exec } from 'child-process-promise';
chai.use(chaiFiles);
describe('cli', () => {
before(() => {
process.chdir(__dirname);
});
it('should run', async () => {
// make a copy of entry file
fs.copySync('./configs/entry/config.version-and-build.xml', './config.xml');
// executes code that changes temp files
await exec('../dist/cli.js -v 2.4.9 -b 86');
// checks if target file and change temp file are equal
expect(file('./config.xml')).to.equal(file('./configs/expected/config.version-and-build.to.version-and-build.xml'));
});
afterEach(() => {
if (fs.existsSync(tempConfigFile)) {
fs.removeSync(tempConfigFile);
}
});
});
How should this be done in Jest? Will I need to load both files and compare the content?

Yes, simply load the contents of each like so:
expect(fs.readFileSync(actualPath)).toEqual(fs.readFileSync(expectedPath));

Related

Testcafe - Test command line argument outside test case

As I'm getting familiar with Testcafe, I'm trying to use a command line argument to give the user more information on how to run tests. For that reason, I'm using the minimist package.
However, I cannot print or use any variables outside the test cases. Please find below my code.
import { Selector } from 'testcafe';
import minimist from 'minimist';
const args = minimist(process.argv.slice(2));
const env = args.env;
console.log('*** A SAMPLE CONSOLE OUTPUT ***'); // does not print
fixture `Getting Started`
.page `http://devexpress.github.io/testcafe/example`;
test('My first test', async t => {
console.log('*** ANOTHER SAMPLE CONSOLE OUTPUT ***'); // prints
await t
.typeText('#developer-name', 'John Smith')
.wait(1000)
.click('#submit-button')
// Use the assertion to check if the actual header text is equal to the expected one
.expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');
});
I want to write an if statement that checks if env === '' or use a default argument.
How can I accomplish this?
However, I cannot print or use any variables outside the test cases.
 
Please use a programming way to run TestCafe.
I've changed you code example (test.js) and created a file that runs TestCafe programmatically (run.js).
Put these files into a folder and perform command 'node run.js --env value' in your terminal.
Then you will see the following output:
'*** A SAMPLE CONSOLE OUTPUT ***'
Getting Started
value
test.js
import { Selector } from 'testcafe';
import minimist from 'minimist';
const args = minimist(process.argv.slice(2));
const env = args.env;
console.log('*** A SAMPLE CONSOLE OUTPUT ***');
fixture `Getting Started`
.page `http://devexpress.github.io/testcafe/example`;
test('My first test', async t => {
console.log(env); // prints
await t
.typeText('#developer-name', 'John Smith')
.wait(1000)
.click('#submit-button')
.expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');
});
run.js
const createTestCafe = require('testcafe');
let runner = null;
createTestCafe('localhost', 1337, 1338, void 0, true)
.then(testcafe => {
runner = testcafe.createRunner();
})
.then(() => {
return runner
.src('test.js')
.browsers('chrome')
.run()
.then(failedCount => {
console.log(`Finished. Count failed tests:${failedCount}`);
process.exit(failedCount)
});
})
.catch(error => {
console.log(error);
process.exit(1);
});
A solution to accomplish this is:
1) Create a separate config.js file that will handle your custom command-line options:
import * as minimist from 'minimist';
const args = minimist(process.argv.slice(2));
// get the options --env=xxx --user=yyy from the command line
export const config = {
env: args.env,
user: args.user,
};
2) In you test file:
remove any code outside the fixture and the test methods.
import the config file and inject it in the TestController context
get the command args via the TestController context
import 'testcafe';
import { Selector } from 'testcafe';
import { config } from './config';
fixture('Getting Started')
.beforeEach(async (t) => {
// inject config in the test context
t.ctx.currentConfig = config;
});
test('My first test', async (t) => {
// retrieve cli args from the test context
const currentConfig = t.ctx.currentConfig;
console.log(`env=${currentConfig.env}`);
});

node - using jest with esm package

I was wondering how I would incorporate the esm package https://www.npmjs.com/package/esm with jest on a node backend.
I tried setting up a setup file with require("esm") and require("esm")(module) at the very top of the file, but it's still giving me the SyntaxError: Unexpected token error.
I would have previously used node -r esm but jest doesn't support this.
When you perform require("esm")(module), think of it as you are creating an esm-transformer function that is pending a file to be transformed into an ES module.
Here's my attempt with node v8+ with:
default jest configuration
default esm configuration
utils-1.js:
export const add = (a, b) => a + b;
utils-2.js:
export const multiAdd = array => array.reduce((sum, next) => sum + next, 0)
_test_/utils-1.assert.js
import { add } from '../utils-1';
describe('add(a,b)', () => {
it('should return the addtion of its two inputs', () => {
expect(add(1,2)).toBe(3);
});
});
_test_/utils-2.assert.js
import { multiAdd } from '../utils-2';
describe('multiAdd(<Number[]>)', () => {
it('should return a summation of all array elements', () => {
expect(multiAdd([1,2,3,4])).toBe(10);
})
});
_test_/utils.test.js
const esmImport = require('esm')(module);
const utils_1 = esmImport('./utils-1.assert')
const utils_2 = esmImport('./utils-2.assert')
Hope this helps!

How do I use a Native Node JS Module (--experimental-modules) with Mocha

I have the following Test Suite...
import Mocha from 'mocha';
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
(()=>{
let mocha = new Mocha();
mocha.addFile(path.resolve(__dirname,'./tests/sampleTest.js'));
mocha.run(failures => {
console.log("Running Mocha");
process.on('exit', () => {
console.log("Ending Mocha");
process.exit(failures ? 1 : 0);
});
});
})();
And the following test file...
const assert = require('assert');
describe('Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal([1,2,3].indexOf(4), -1);
});
});
});
This works great, however, I want to convert it over to a module JS (.mjs) so I can import other modules in the test. I try this by changing the extension and making the code...
import assert from 'assert';
describe('Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal([1,2,3].indexOf(4), -1);
});
});
});
When I run this I get...
Must use import to load ES Module: **/src/test/js/webdriver/tests/sampleTest.mjs
I also tried just importing it like this...
import Mocha from 'mocha';
import path from 'path';
import './tests/sampleTest.mjs';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
(()=>{
let mocha = new Mocha();
// mocha.addFile(path.resolve(__dirname,'./tests/sampleTest.mjs'));
mocha.run(failures => {
console.log("Running Mocha");
process.on('exit', () => {
console.log("Ending Mocha");
process.exit(failures ? 1 : 0);
});
});
})();
But then I get...
ReferenceError: describe is not defined
I also tried
import mocha from "mocha"
...
mocha.describe(...)
But that also did not work.
How do I load another module into mocha?
The only workaround for now is https://www.npmjs.com/package/mjs-mocha
I hope this link is suitable here cause npm does save packages forever. Feel free to refer to package docs and sources

Configuring jsdom in Jest across multiple tests without using modules

I want to test scripts in an environment where we can not export modules. I have installed Jest version 23.1.0 and there aren't other packages in my package.json file.
Using jsdom 'old' api I have come up with a solution that works as expected:
script.js
var exVar = "test";
script.test.js
const jsdom = require('jsdom/lib/old-api.js');
test('old jsdom api config', function(done) {
jsdom.env({
html: "<html><body></body></html>",
scripts: [__dirname + "/script.js"],
done: function (err, window) {
expect(window.exVar).toBe("test");
done();
}
});
});
However with this implementation I have to re-write the config for every test, because it looks like the jsdom config gets re-written every time.
What I have tried
So far I have tried running this configuration:
const jsdom = require('jsdom/lib/old-api.js');
jsdom.env({
html: "<html><body></body></html>",
scripts: [__dirname + "/script.js"],
done: function (err, window) {
console.log('end');
}
});
with this test:
test('old jsdom api config', function(done) {
expect(window.exVar).toBe("test");
done();
});
in different ways: inside beforeAll, inside a script linked through setupFiles or through setupTestFrameworkScriptFile in the Jest configuration object, but still nothing works.
Maybe I could extend jest-environment as suggested in the docs, but I have no idea of the syntax I should be using, nor of how to link this file to the tests.
Thanks to my co-worker Andrea Talon I have found a way of using the same setup for different tests (at least inside the same file) using the 'Standard API' (not the 'old API').
Here is the complete test file.
const {JSDOM} = require("jsdom")
const fs = require("fs")
// file to test
const srcFile = fs.readFileSync("script.js", { encoding: "utf-8" })
// the window
let window
describe('script.js test', () => {
beforeAll((done) => {
window = new JSDOM(``, {
runScripts: "dangerously"
}).window
const scriptEl = window.document.createElement("script")
scriptEl.textContent = srcFile
window.document.body.appendChild(scriptEl)
done()
})
test('variable is correctly working', (done) => {
expect(window.exVar).toBe("test");
done()
})
})
Additional setup
In order to load multiple scripts I have created this function which accepts an array of scripts:
function loadExternalScripts (window, srcArray) {
srcArray.forEach(src => {
const scriptEl = window.document.createElement("script")
scriptEl.textContent = src
window.document.body.appendChild(scriptEl)
});
}
So instead of appending every single script to the window variable I can load them by declaring them at the top of the file like this:
// files to test
const jQueryFile = fs.readFileSync("jquery.js", { encoding: "utf-8" })
const srcFile = fs.readFileSync("lib.js", { encoding: "utf-8" })
and then inside the beforeAll function I can load them altogether like this:
loadExternalScripts(window, [jQueryFile, srcFile])

Jest - Testing Module Multiple Times in One Test Suite

I have a TypeScript module (should be irrelevant, as I think this affect JS too) and I'm trying to test a module I have. The module imports lots of data from external files and chooses which data should be returned based on the a variable.
I'm attempting to run some tests where I update that variable, re-require the module and run further tests in one file. But my issue is that the require of the file only runs once. I guess it's being cached. Is it possible to tell Jest's require function not to cache or to clear the cache between tests?
Here's some stripped back code of what I'm trying to achieve:
module.ts
import { getLanguage } from "utils/functions";
import * as messagesEn from "resources/translations/en";
import * as messagesFr from "resources/translations/fr";
// Determine the user's default language.
const language: string = getLanguage();
// Set messages based on the language.
let messages: LocaleMessages = messagesEn.default;
if (languageWithoutRegionCode === "fr") {
messages = messagesFr.default;
}
export { messages, language };
test.ts
import "jest";
// Mock the modules
const messagesEn = { "translation1": "English", "translation2": "Words" };
const messagesFr = { "translation1": "Francais", "translation2": "Mots" };
const getLangTest = jest.fn(() => "te-ST");
const getLangEn = jest.fn(() => "en-GB");
const getLangFr = jest.fn(() => "fr-FR");
jest.mock("resources/translations/en", () => ({"default": messagesEn}));
jest.mock("resources/translations/fr", () => ({"default": messagesFr}));
jest.mock("utils/functions", () => ({
getLanguage: getLangTest
})
);
describe("Localisation initialisation", () => {
it("Sets language", () => {
const localisation = require("./localisation");
expect(getLangTest).toHaveBeenCalled();
expect(localisation.language).toEqual("te-ST");
expect(localisation.messages).toEqual(messagesEn);
});
it("Sets english messages", () => {
// THIS GETS THE MODULE FROM THE CACHE
const localisation = require("./localisation");
expect(getLangEn).toHaveBeenCalled();
expect(localisation.language).toEqual("en-GB");
expect(localisation.messages).toEqual(messagesEn);
});
it("Sets french messages", () => {
// THIS GETS THE MODULE FROM THE CACHE
const localisation = require("./localisation");
expect(getLangFr).toHaveBeenCalled();
expect(localisation.language).toEqual("fr-FR");
expect(localisation.messages).toEqual(messagesFr);
});
});
I'm aware the second and third tests won't work anyway as I'd need to update the "utils/functions" mock. The issue is that the code in module.ts only runs once.
So, many thanks to the Jest folks on Discord. It's possible to actually clear the modules from the cache with the jest.resetModules() function.
So my test.ts file will look as follows:
describe("Localisation initialisation", () => {
beforeEach(() => {
jest.resetModules();
});
it("Sets language", () => {
const localisation = require("./localisation");
// Perform the tests
});
it("Sets english messages", () => {
const localisation = require("./localisation");
// Perform the tests
});
it("Sets french messages", () => {
const localisation = require("./localisation");
// Perform the tests
});
});
The beforeEach() call to jest.resetModules() ensures we're re-running the code in the module.

Categories