Print the jest coverage table using exec via script - javascript

I am trying to create a utility to take the windows relative path from VSCode or IntelliJ and replace the forward slash from the path with backslash and execute the jest command to produce the coverage of the files mentioned in the argument to a script.
This is what I tried:
Script_file.js
const yargs = require('yargs');
const exec = require('child_process').exec;
const options = yargs
.usage('Some info')
.option('t', {some_object})
.option('m', {some_object})
.argv;
const tp = options.t.replace(/\\/g, '/');
const mp = options.m.replace(/\\/g, '/');
exec(`jest ${tp} --coverage --collectCoverageFrom=${mp} --colors`, (error, stdout, stderr) => {
if(error){
console.log('err');
}
console.log(stdout);
})
My script in package.json
"test:CoverageFile": "node Script_file.js",
Command
npm run test:CoverageFile -- -t=windows\style\file\path\for\test -m=windows\style\file\path\for\file\to\get\coverage\from
Now, everything is fine and I'm getting the output as expected too except the marked area in the image attached below[Image is just for reference]:
My question is how can I print this table as well in the output? I'll be highly obliged for any help.
EDIT:
I also tried hooking up the --coverageReporters flag with jest command using various available options but to no avail.

Related

'.' is not recognized as an internal or external command thrown when used in exec(), but not when run from command line

The following is part of a script that is run using npm run test.
async setup() {
process.env.DATABASE_URL = this.databaseUrl;
this.global.process.env.DATABASE_URL = this.databaseUrl;
await exec(`./node_modules/.bin/prisma migrate up --create-db --experimental`);
return super.setup();}
This throws the following error
Command failed: ./node_modules/.bin/prisma migrate up --create-db --experimental
'.' is not recognized as an internal or external command,
operable program or batch file.
When run from the cmd the command works as expected. What is the correct way to reference the binary file within exec()? I am using windows incase that is relevant.
Solution with help from #derpirscher.
const path = require("path");
const prismaBinary = "./node_modules/.bin/prisma";
await exec(
`${path.resolve(prismaBinary)} migrate up --create-db --experimental`
);

How to output a consoles log to another file as regular text

I'm trying to print the result of my console.log to another .txt file, how would I make this happen? this is what my console.log looks like this: https://imgur.com/o2Vo471
I'm wanting this printed as regular text to an output file e.g 'output.txt'
I recommend to use Winston to achieve this.
You can set up Winston Transports to output in file winston.add(winston.transports.File, options)
Or if you don't wanna add any npm modules to your app you can just do this
var fs = require('fs');
module.exports = function(text) {
fs.appendFile('output.txt', text + '\n', function (err) {
if (err) throw err;
});
};
And save this to a file in your project directory, for example NameOfYourFile.js.
Then you can just require it in a file that you wanna make output from
var loger = require('./NameOfYourFile');
loger('Logs');
loger('Output');
loger('Working');
And just use loger instead of console.log. You also can easily rename it.
TypeScript version
First, install node modules
npm install #types/node --save-dev
Then create a file for your module, for example, NameOfYourFile.ts
import * as fs from 'fs';
export default function(text) {
fs.appendFile('output.txt', text + '\n', function (err) {
if (err) throw err;
});
};
Then you can import it like this
import loger from './NameOfYourFile';
loger('Logs');
loger('Output');
loger('Working');
Can you rewrite your program as a node app and then just run it from the Terminal window instead? Then, you wouldn't need to wrestle with this problem of getting your console output into a file... you could use node's fs instead (Node.js Write a line into a .txt file)
This answer works, but it isn't what i'm aiming for it will work for most other people i'd assume. you're gonna want to run your program like so:
npm start > output.txt
this will print your console output to the output.txt file I still need to achieve this with node fs so i'd appreciate anymore answers

Getting test results when creating a Karma server programmatically

I am trying to run multiple Karma test files in parallel from inside a Node script and get to know which tests are passing or failing. Right now what I have is this:
const exec = require("child_process").exec;
exec("karma start " + filename, (error, stdout, stderr) => {
// handle errors and test results...
});
The code above works well, and I can get the information on tests passed or failed from stdout. However, it requires having installed Karma and all of the associated dependencies (reporters, browser launchers, etc.) globally. I am looking for a solution that doesn't require me to install all dependencies globally.
My first thought was this:
const karma = require("karma");
const server = new karma.Server(config, () => {
// some logic
});
However, when trying this other approach, I have been unable to gather the test results programmatically.
When using new karma.Server(), is there any way in which I could know which tests have passed or failed (and, ideally, a stack trace of the error)? Alternatively, is there any other way in which I can execute my tests and get the desired information programmatically without the need to install dependencies globally?
Actually, changing the exec line to this seems to do the trick:
exec("node node_modules/karma/bin/karma start " + filename, (error, stdout, stderr) => {
It turns out I'd only need to run the locally installed version of Karma instead of the global one. :-)

How do I specify a single file to be seed only

I am using knex for seeding and I have a folder called development where I have all the seeds files.
What I would want is: How to seed single file.
The command I am using is: knex seed:run --env=development
But this command is to seed all the files and I get duplicate rows on db.
Suppose I have created seed files yesterday, and I seed them, today I want to add another seed file, which I only want to seed this file, not the files from yesterday.
An example from Laravel is: php artisan db:seed --class=ProductTableSeeder
Thanks
For those of you checking this in 2019+
According to the knex documentation
To run a specific seed file, execute:
$ knex seed:run --specific=seed-filename.js
Just move your scripts to another folder except the desired script, run the seed and copy the scripts back.
The seed API only has two commands, make and run. This is from the docs.
runknex.seed.run([config])
Runs all seed files for the current environment.
So all scripts will be executed on each run
Don't work: knex seed:run --specific=seed-filename.js
create in DB knex_seed_lock table
Add this to seed file:
const file_name = path.basename(__filename)
const seedIsExist = await knex('knex_seeds_lock').where({ file_name }).first()
if (seedIsExist) {
return
}
And add this to the end of the file:
await knex('knex_seeds_lock').insert({ file_name })
As a result, in the database you will get all the seed ​​that you already ran earlier
Personally I just wrap my promise in exports.up/down in an if (boolean) {...} and switch the ones to false that I don't want to run.
The solution from Artem works fine:
You just need to create table: knex_seeds_lock
The code that i used is here:
`
const path = require('path')
exports.seed = async (knex) => {
try {
const file_name = path.basename(__filename)
const seedIsExist = await knex('knex_seeds_lock').where({ file_name }).first()
if (seedIsExist) {
return
} else {
await knex('users_types').del();
await knex('knex_seeds_lock').insert({ file_name })
await knex('users_types').insert([
{name: 'client'},
{name: 'driver'},
{name: 'admin'}
]);
return;
}
} catch (err) {
console.log("ERROR SEEDING")
console.log(err);
}
}`
#Madison_Lai's answer is correct, but similar to one comment on that answer my --specific flag was also being ignored.
TLDR: Adding the -- separator solved my issue.
npm run knex seed:run -- --specific=seed-filename.js
Details:
In my case, the knex script in my package.json included a passed argument, which ended up causing ordering issues when I tried to pass additional arguments via CLI.
In package.json
"scripts": {
"knex": "./path/to/knex --knexfile=./path/to/knexfile.js"
}
In CLI,
npm run knex seed:run --specific=seed-filename.js
was getting parsed as below, completely losing the --specific argument
./path/to/knex --knexfile=./path/to/knexfile.js "seed:run"
Prefixing -- before passing the additional argument (as recommended here) solved the issue for me
npm run knex seed:run -- --specific=seed-filename.js

Passing stdout colored output to grunt output

I'm trying to create a grunt custom task that runs mocha tests but I can't figure out how to have grunt take the colored output from mocha and display it as it does when running the mocha command directly. Ie: grunt strips out the colors or does not pass them through. Here's the grunt task:
var exec = require("child_process").exec;
grunt.registerTask('mocha', 'Run unit (Mocha) tests.', function () {
var done = this.async();
var cmd = "mocha -R Spec tests/mocha/*.js";
exec(cmd, function (error, stdout, stderr) {
if (stdout) {
grunt.verbose.or.write(stdout);
done();
}
});
});
I realize there's a grunt-mocha plugin I could use (and have used) but I'm trying to eliminate dependencies and will also be doing some customization on this task.
Thanks!
This is mostly a duplicate of this question.
You need to add --colors to force Mocha to output ANSI color codes, otherwise it disables colors automatically since it isn't outputting to an actual terminal.
var cmd = "mocha --colors -R Spec tests/mocha/*.js";

Categories

Resources