I want to use jest.runCLI() in gulp for executing only a changed test.
How can I do this?
How can I run just one test with jest.runCLI()?
Jest has a CLI option to run only changed files (based on the git repository status).
The command line jest --onlyChanged becomes programmatically:
jest.runCLI({'onlyChanged': true}, __dirname, function (success) {...});
Using the terminal, jest uses non-hyphenated options to specified filenames:
jest test1 runs only test1.js
jest test1 test2 runs test1.js and test2.js
jest-cli uses optimist to parse options and non-hyphenated option are mapped to the underscore option (_):
jest.runCLI({'_': ['test1']}, __dirname, function (success) {...}); runs only test1.js
jest.runCLI({'_': ['test1', 'test2']}, __dirname, function (success) {...}); runs test1.js and test2.js
Related
I would like to know if it is possible to execute something if all my test files have passed with mocha.
Below: is my index.js file which is run by mocha (in order to get the order I want)
require('dotenv').config();
const logger = require('../toolkits/logger');
//silent mode for testing
logger.transports.forEach((t) => (t.silent = true));
require("./broker.test");
require("./mongo.test");
require("./auth.test");
require("./meal.test");
require("./bowl.test");
I want to process.exit(0) if the tests passed (to integrate it into gitlab CI).
I succeded in check if a test hasn't passed by doing this :
afterEach(function(){
if (this.currentTest.state === "failed")
process.exit(1);
})
But I can't detect if all the tests passed.
I can't just process.exit(0) after requiring all the tests because some of them are asynchronous.
Do you have an idea how I can do that?
! Update !
I found out that I could pass the --exit argument when running mocha from npm :
mocha file --exit
I dont know why the test runner wont detect my tests.
npm test
myproject#1.0.0 test C:\Users\sjsui\Desktop\git_workshop\myproject
mocha ./built/source
0 passing (4ms)
PS C:\Users\sjsui\Desktop\git_workshop\myproject>
I know that test is the default folder that mocha searches for so that is how I structured my project.
built
\--source
\--test
\--test.js
here is my test.js file
describe("consumer tests", function()
{
it("runs bad request tests", (done) => {
let tests = new badrequesttests()
iteratebadtests(tests, done)
})
it("normal consumer tests", (done) => {
let tests = new normaltests()
iteratenormaltests(tests, done)
})
it("abnormal consumer tests", (done) => {
let tests = new unauthorizedtests()
iterateunauthorizedtests(tests, done)
})
})
npm scripts section in package.json
"scripts": {
"test": "mocha ./built/source"
},
as a side note, break points wont hit inside the test (visual studio code debug task -> mocha)
I think your test scripts are not detected y mocha because by default mocha does not scan sub-directories and your tests are inside a subdirectory of path you are passing at the time of invking mocha. There are two ways to resolve this.
Provide the path of test folder to mocha as below
mocha ./built/source/test
Trigger mocha tests with recursive flag. Using this flag mocha will scan the subdirectories of the path you provide
mocha ./built/source --recursive
I think this should solve your problem
You can pass the directory to search for your test files like below:
mocha -- ./built/source/**/*.test.js
This will check for all test files ending with .test.js in their file name in any directory within the source directory.
mocha -- ./built/source/*.test.js
That will check for test files within the source directory.
Jest provides some useful methods for executing something before your tests: beforeEach() and beforeAll(). Jest docs on setup
The issue with these is they can only be placed inside of a describe block. So if I have many files, each with their own describe block, I need to place to beforeEach() in every file.
How can I run some code before & after every test, while only adding it once (instead of adding it in every describe block)?
You can try the globalSetup Jest config key. It is an optional key and it can be used to run an async function once before all test suites.
Please see https://github.com/facebook/jest/blob/master/docs/Configuration.md#globalsetup-string
Example of setting up globalSetup in package.json:
jest: {
globalSetup: "./path-to-global-setup.js"
}
... or in jest.config.js:
module.exports = {
globalSetup: "./path-to-global-setup.js"
};
Example of global-setup.js file:
module.exports = async function() {
// do something
};
This file will not be transformed by babel when you run your test suite.
I want to use Circle CI to integrate a git project.
I'm using mocha for my tests .
What i want to do?
When running npm test I want:
my node server to start
my test file to run
How can I run a single npm test command to run both node and my mocha tests which are already wrapped in a single index.js file.
I have tried this in my package.json:
"scripts": {
"test": "node server/app.js & mocha server/tests/index.js",
"start": "node server/app.js",
"postinstall": "bower install"
}
The problems with the above
My server takes some time to start and the tests fail since they run before the server starts
Is there a standard way to run a server and the tests with a single command but I'm missing something?
If it is possible at all in your case I'd suggest using something like supertest to do the testing. This way, you can avoid having to start a server before starting the test.
I understand that there are scenarios where using supertest is not possible. In such case, you could poll your server in a before hook before all tests to wait until it is ready:
before(function (done) {
// Set a reasonable timeout for this hook.
this.timeout(5000);
function check() {
if (serverIsReady()) {
done();
return;
}
// The server is no ready, check again in 1/10th of a second.
setTimeout(check, 100);
}
check(); // Start checking.
});
I'm not sure what serverIsReady should be precisely in your case. It could be an attempt at getting a trivial path from your server like issuing a GET on the path /.
I think the key is to run your node server in your test, rather than trying to initialise it in another process.
Your mocha test should start with a require to your app, then each
of your tests can interact with it.
For example:
var http = require('http');
var server = http.createServer(function(req, res){
res.end('Hello World\n');
})
server.listen(8888);
describe('http', function(){
it('should provide an example', function(done){
http.get({ path: '/', port: 8888 }, function(res){
expect(res).to.have.property('statusCode', 200);
done();
})
})
})
What I do when running a test that needs certain pre-requisites is use mochas beforeEach() functionality.
From the documentation
You may also pick any file and add “root”-level hooks. For example, add beforeEach() outside of all describe() blocks. This will cause the callback to beforeEach() to run before any test case, regardless of the file it lives in (this is because Mocha has an implied describe() block, called the “root suite”).
beforeEach(function() {
console.log('before every test in every file');
});
In the before each code block you can run your command to start the server
using for example the exec library from npm
https://www.npmjs.com/package/exec
This will ensure your server is running before your tests are run allowing you to simply run npm test.
How do I setup Karma to run my backend unit tests (written with Mocha)? If I add my backend test script to the files = [], it fails stating that require is undefined.
You don't. Karma is only for testing browser-based code. If you have a project with mocha tests on the backend and karma/mocha on the front end, try editing your package.json under scripts to set test to: mocha -R spec && karma run karma.con
Then, if npm test returns true, you'll know it's safe to commit or deploy.
It seems like it cannot be done (thanks #dankohn). Here is my solution using Grunt:
Karma: update your karma.conf.js file
set autoWatch = false;
set singleRun = true;
set browsers = ['PhantomJS']; (to have inline results)
Grunt:
npm install grunt-contrib-watch grunt-simple-mocha grunt-karma
configure the two grunt tasks (see grunt file below)
Gruntfile.js:
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-simple-mocha');
grunt.loadNpmTasks('grunt-karma');
grunt.initConfig({
simplemocha: {
backend: {
src: 'test/server-tests.js'
}
},
karma: {
unit: {
configFile: 'karma.conf.js'
}
}
});
// Default task.
grunt.registerTask('default', ['simplemocha', 'karma']);
};
Grunt (optional): configure grunt-watch to run after changing spec files or files to be tested.
run all using grunt command.