This is my gulpfile
gulp.task('lint', function () {
gulp.src('./src/nodeuii/**/*.js')
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
But:
No ESLint configuration found
gulp.task('lint', function () {
gulp.src('./src/nodeuii/**/*.js')
.pipe(eslint({
configFile: 'eslintrc.js'
}))
});
need a configFile
Related
What I test: An express server endpoints
My goal: automate API tests in a single script
What I do: I launch the express server in a NodeJS child process and would like to wait for it to be launched before the test suite is run (frisby.js endpoints testing)
What isn't working as expected: Test suite is launched before Promise resolution
I rely on the wait-on package which server polls and resolves once the resource(s) is/are available.
const awaitServer = async () => {
await waitOn({
resources: [`http://localhost:${PORT}`],
interval: 1000,
}).then(() => {
console.log('Server is running, launching test suite now!');
});
};
This function is used in the startServer function:
const startServer = async () => {
console.log(`Launching server http://localhost:${PORT} ...`);
// npmRunScripts is a thin wrapper around child_process.exec to easily access node_modules/.bin like in package.json scripts
await npmRunScripts(
`cross-env PORT=${PORT} node -r ts-node/register -r dotenv/config src/index.ts dotenv_config_path=.env-tests`
);
await awaitServer();
}
And finally, I use this in something like
describe('Endpoints' () => {
beforeAll(startTestServer);
// describes and tests here ...
});
Anyway, when I launch jest the 'Server is running, launching test suite now!' console.log never shows up and the test suite fails (as the server isn't running already). Why does jest starts testing as awaitServer obviously hasn't resolved yet?
The npmRunScripts function works fine as the test server is up and running a short while after the tests have failed. For this question's sake, here's how npmRunScripts resolves:
// From https://humanwhocodes.com/blog/2016/03/mimicking-npm-script-in-node-js/
const { exec } = require('child_process');
const { delimiter, join } = require('path');
const env = { ...process.env };
const binPath = join(__dirname, '../..', 'node_modules', '.bin');
env.PATH = `${binPath}${delimiter}${env.PATH}`;
/**
* Executes a CLI command with `./node_modules/.bin` in the scope like you
* would use in the `scripts` sections of a `package.json`
* #param cmd The actual command
*/
const npmRunScripts = (cmd, resolveProcess = false) =>
new Promise((resolve, reject) => {
if (typeof cmd !== 'string') {
reject(
new TypeError(
`npmRunScripts Error: cmd is a "${typeof cmd}", "string" expected.`
)
);
return;
}
if (cmd === '') {
reject(
new Error(`npmRunScripts Error: No command provided (cmd is empty).`)
);
return;
}
const subProcess = exec(
cmd,
{ cwd: process.cwd(), env }
);
if (resolveProcess) {
resolve(subProcess);
} else {
const cleanUp = () => {
subProcess.stdout.removeAllListeners();
subProcess.stderr.removeAllListeners();
};
subProcess.stdout.on('data', (data) => {
resolve(data);
cleanUp();
});
subProcess.stderr.on('data', (data) => {
reject(data);
cleanUp();
});
}
});
module.exports = npmRunScripts;
I found the solution. After trying almost anything, I didn't realize jest had a timeout setup which defaults at 5 seconds. So I increased this timeout and the tests now wait for the server promise to resolve.
I simply added jest.setTimeout(3 * 60 * 1000); before the test suite.
In my case, it caused by the flaw of the beforeAll part. Make sure the beforeAll doesn't contain any uncaught exceptions, otherwise it will behaves that the testing started without waiting for beforeAll resolves.
After much digging I found a reason for why my beforeAll didn't seem to be running before my tests. This might be obvious to some, but it wasn't to me.
If you have code in your describe outside an it or other beforeX or afterY, and that code is dependent on any beforeX, you'll run into this problem.
The problem is that code in your describe is run before any beforeX. Therefore, that code won't have access to the dependencies that are resolved in any beforeX.
For example:
describe('Outer describe', () => {
let server;
beforeAll(async () => {
// Set up the server before all tests...
server = await setupServer();
});
describe('Inner describe', () => {
// The below line is run before the above beforeAll, so server doesn't exist here yet!
const queue = server.getQueue(); // Error! server.getQueue is not a function
it('Should use the queue', () => {
queue.getMessage(); // Test fails due to error above
});
});
});
To me this seems unexpected, considering that code is run in the describe callback, so my impression was that that callback would be run after all beforeX outside the current describe.
It also seems this behavior won't be changed any time soon: https://github.com/facebook/jest/issues/4097
In newer versions of jest (at least >1.3.1) you can pass a done function to your beforeAll function and call it after everything is done:
beforeAll(async (done) => {
await myAsyncFunc();
done();
})
it("Some test", async () => {
// Runs after beforeAll
})
More discussions here: https://github.com/facebook/jest/issues/1256
We have some simple "is this really working" chai tests of an electron app using spectron and WebdriverIO. The example code we started with is from
https://github.com/jwood803/ElectronSpectronDemo as reported in https://github.com/jwood803/ElectronSpectronDemo/issues/2, the chai-as-promised tests are not catching mismatches, so I thought I would add some additional tests to find out why Chai is not failing tests where the electron app has text that doesn't match the expected unit test text.
Let's start with something really simple, the rest of the code is at https://github.com/drjasonharrison/ElectronSpectronDemo
describe('Test Example', function () {
beforeEach(function (done) {
app.start().then(function() { done(); } );
});
afterEach(function (done) {
app.stop().then(function() { done(); });
});
it('yes == no should fail', function () {
chai.expect("yes").to.equal("no");
});
it('yes == yes should succeed', function () {
chai.expect("yes").to.equal("yes");
});
The first unit test fails, the second succeeds.
And when we put the assertion into a function this still detects the failure:
it('should fail, but succeeds!?', function () {
function fn() {
var yes = 'yes';
yes.should.equal('no');
};
fn();
});
So now into the world of electron, webdriverio, and spectron, the application title is supposed to be "Hello World!", so this should fail, but it passes:
it('tests the page title', function () {
page.getApplicationTitle().should.eventually.equal("NO WAY");
});
Hmm, let's try a more familiar test:
it('should fail, waitUntilWindowLoaded, yes != no', function () {
app.client.waitUntilWindowLoaded().getTitle().then(
function (txt) {
console.log('txt = ' + txt);
var yes = 'yes';
yes.should.equal('no');
}
);
});
Output:
✓ should fail, waitUntilWindowLoaded, yes != no
txt = Hello World!
It succeeds? What? Why? How?
Found it! If you look at https://github.com/webdriverio/webdriverio/blob/master/examples/standalone/webdriverio.with.mocha.and.chai.js
you will see that you need to return the promise from each of the tests. This is typical for async chai/mocha tests:
it('tests the page title', function () {
return page.getApplicationTitle().should.eventually.equal("NO WAY");
});
If you do that, then the chai test is actually correctly evaluated.
First, while I'm an experienced programmer, I'm relatively new to node, and very new to mocha, so my issue may be ME! In which case, I'll be happy to find that out too!
Some code I'm writing makes use of an npm module which contains a call to fs.exists. I get different results when I run a test with fs.exists when run via node vs when run vs mocha; in my opinion, I should be receiving the same answer; the file does exists, so the result should be true in both cases, but instead, it's true when invoked via node, and false when invoked via mocha. Well, it's not functioning correctly.
I'm aware that fs.exists is deprecated, but that's in the npm module I'm using, so unless I modify the module, that's what I'm using.
The difference is associated with how I invoke mocha.
Per some site recommendations, I edited my package.json file to include, in the 'scripts' section, the following statement: "test": "mocha test", and I have placed my tests in this 'test' directory. This is invoked via npm test.
After experiencing problems, I also installed did npm install -g mocha.
My test file is testVersion.js
The result is that I get different answers when I invoke one of the following three ways when invoking fs.exists via node, npm test, and mocha testVersion.js; I'm expecting 'true':
- node testVersion.js returns true - it finds the file.
- mocha testVersion.js returns true - it finds the file.
- npm test returns false - it does not find the file.
I'm suspecting that maybe different versions of mocha or node are being invoked on me, but don't have enough experience to be able to determine this on my own.
So my question is: why am I getting different results?
Here's my code for testVersion.js
var expect = require('chai').expect;
var assert = expect.assert;
var fs = require("fs");
var isInTest = typeof global.it === 'function'; //exe via mocha or node
console.log('isInTest mode: ', isInTest);
if(!isInTest) {
console.log('NOT TEST MODE: invoking fs.exists');
fs.exists("testVersion.js", function(info) {
console.log('NOT TEST MODE: fs.exists callback RAN.');
console.log('NOT TEST MODE: fs.exists: should be true and is: ', info);
})
}
if(isInTest) {
describe("Test Mocha and fs.exists issue", function() {
it("Test that file self exists.", function() {
console.log('TEST MODE: invoking fs.exists');
expect(fs.exists("testVersion.js", function(result) {
console.log('TEST MODE: fs.exists callback RAN.');
console.log('TEST MODE: fs.exists: should be true, and is: ', result);
return true;
})).to.equal(true);
});
});
};
After a lot of testing work, I believe my problem was because of async calls associated with fs.exists. At any rate, the following is working for me, and I wanted to document it in case it helps anyone else.
var assert = require('assert');
var fs = require('fs');
fs.existsSync("bbq.js", function(result) {
console.log('False: fs.exists(bbq.js) says: ', result);
})
fs.existsSync("test2.js", function(result) {
console.log('True: fs.exists(test2.js) says: ', result);
})
describe('Testing Synch fs.existsSync() ===', function() {
describe('False: fs.exists(bbq.js)', function() {
it("This assertion should pass, as we are asserting false on file that doesn't exist.", function() {
assert.equal(false, fs.existsSync(__dirname + "/bbq.js", function(result) { return result;}))
});
});
describe('Testing Synch fs.existsSync(test2.js method A)', function() {
it("This assertions should pass as we are asserting true on file that does exist", function() {
assert.equal(true, fs.existsSync(__dirname + "/test2.js", function(result) {
return result;
}));
});
});
describe('Testing Synch fs.existsSync(test2.js method B)', function() {
it("This assertions should pass as we are are asserting true on file that does exist using callback", function() {
fs.existsSync(__dirname + "/test2.js", function(result) {
assert.equal(true, result);
});
});
});
});
////////////////////
describe('Asynch test of fs.exists() === some results are UNDEFINED because of async', function() {
describe('False: fs.exists(bbq.js)', function() {
it("This assertion should pass as we are expecting undefined result due to async.", function() {
assert.equal(undefined, fs.exists(__dirname + "/bbq.js", function(result) { return result;}))
});
});
describe('True: fs.exists(test2.js method A)', function() {
it("This assertion should pass as we are expecting undefined result due to async.", function() {
assert.equal(undefined, fs.exists(__dirname + "/test2.js", function(result) {
return result;
}));
});
});
describe('True: fs.exists(test2.js method B)', function() {
it("This equal assertion passes, because of use of callback waits for response.", function() {
fs.exists(__dirname + "/test2.js", function(result) {
assert.equal(true, result);
});
});
});
});
I'm having a few issues with r.js I'm hoping someone can shed some light on.
Consider the following shim:
shim: {
plugin: ['jquery'],
plugin2: ['jquery', 'plugin']
}
And the following arbitrary plugins (note: they don't need to be jQuery plugins, but 2 must depend on 1).
Plugin 1:
(function ($) {
$.test = function () {
console.log('from plugin 1');
}
})(jQuery);
Plugin 2:
(function ($) {
$.test();
})(jQuery);
r.js will build the following:
(function ($) {
$.test = function () {
console.log('from plugin 1');
}
})(jQuery);
define("plugin", function(){});
(function ($) {
$.test();
})(jQuery);
define("plugin2", function(){});
Which is great - everything is in the correct order.
However, if I need to set
wrapShim: true
in the build config, I get this as an output:
(function(root) {
define("plugin", [], function() {
return (function() {
(function ($) {
$.test = function () {
console.log('from plugin 1');
}
})(jQuery);
}).apply(root, arguments);
});
}(this));
(function(root) {
define("plugin2", [], function() {
return (function() {
(function ($) {
$.test();
})(jQuery);
}).apply(root, arguments);
});
}(this));
I'm not sure if I'm misreading the point of setting wrapShim to true, but shouldn't this be compiling to:
define("plugin", ["jquery"], function() ...
and
define("plugin2", ["jquery", "plugin"], function() ...
?
It appears that wrapShim is totally ignoring dependencies set in the shim.
This was a bug, fix tracked here:
https://github.com/jrburke/r.js/issues/813
On further inspection while writing this post it appears that if dependencies are listed in the longer form of:
shim: {
plugin: {
deps: ['jquery']
},
plugin2: {
deps: ['jquery', 'plugin']
}
}
then the dependencies are injected correctly.
I'm trying to use Intern to author a first functional test, and I can't get around the following problem: when running the following test script
define(["intern!object",
"intern/chai!assert"
], function(registerSuite, assert){
registerSuite({
name: "suite",
"test": function(){
var browser = this.remote;
console.log("HELLO !");
browser.get("http://www.google.com", function() {
console.log("PAGE LOADED !");
browser.waitForCondition("!!window.document.gbqf", 1000, function(err, value){
console.log("LET'S BEGIN... ");
browser.eval("window.document.gbqf", function(err, value){
console.log("BYE BYE !");
browser.quit();
});
});
});
}
});
});
in chrome, using selenium server standalone 2.32.0 and chromedriver 26.0.1383.0 for windows, my test never end and the last message displayed in the console is "PAGE LOADED !".
Does anyone has an idea of how I'm suppose to write this test, or have a link to some proper (real life) functional tests examples ?
Thanks for your help,
Sebastien
The functional interface does not use callback arguments, it uses promises instead. Your code should look like this:
define([
"intern!object",
"intern/chai!assert"
], function (registerSuite, assert) {
registerSuite({
name: "suite",
"test": function () {
var browser = this.remote;
console.log("HELLO !");
return browser
.get("http://www.google.com")
.then(function () {
console.log("PAGE LOADED !");
})
.waitForCondition("!!window.document.gbqf", 1000)
.then(function () {
console.log("LET'S BEGIN... ");
})
.eval("window.document.gbqf")
.then(function (value) {
console.log("BYE BYE !");
});
});
}
});
});
Note in particular:
The last promise chain from this.remote is returned by the test function to indicate to Intern that the test is asynchronous
waitForCondition does not return a value
You should never call quit yourself; this is handled by Intern once the test is complete