Where can i find documentation for builder in yargs npm? - yargs

Does anyone know npm yargs very well? I am using this package for command line argument thing.. BUT I cannot find explanation for "builder". Where can i get this?
yargs.command({
command: 'test',
describe: 'testing a note',
builder:{
sample:{
describe: 'Note content',
demandOption: true,
type: 'string'
},
},
handler(argv){
notes.addNote(argv.title, argv.content);
}
})

The builder pattern can help with giving more context with documentation help messages on using multiple commands that can be used.
We would normally use the lambda function version rather than the object version.
For an example, one application can support a number of "commands". These commands would have different bits of functionality associated with the same application.
Below is a simple get/post example that the user can do:
$ node src/index.js get
$ node src/index.js post "" 5001
The get and post after index.js is what yargs considers commands.
One way you could implement this in yargs is:
require('yargs') // eslint-disable-line
.command('post data [port]', 'post some data', yargs => {
yargs.positional('data', {
describe: 'post string',
require: true
})
.positional('port', {
require: false,
describe: 'port to bind on',
default: 8080
})
})
.command('get [port]', 'get some data', yargs => {
yargs.positional('port', {
require: false,
describe: 'port to bind on',
default: 8080
})
})
.option('verbose', {
alias: 'v',
type: 'boolean',
description: 'Run with verbose logging'
})
.argv
So when requesting help information, you can do the following:
$ node src/index.js --help
index.js [command]
Commands:
index.js serve [port] start the server
index.js post data [port] post some data
Options:
--help Show help [boolean]
--version Show version number [boolean]
-v, --verbose Run with verbose logging [boolean]
You can then drill into the help information further:
$ node src/index.js post --help
index.js post data [port]
post some data
Positionals:
data post string [required]
port port to bind on [default: 8080]
This shows the specific help for the post command.
Hence, the command builder pattern allows us to pass any number of commands to an application and provide argument documentation thereof.
It's quite useful when you have to support a number of disparate commands that need their own arguments.
So a long way round to answer the question on where to get more documentation is that if you use the lambda version, the yargs main object is passed to you and you can use all the usual yargs parameters to describe your parameters per command.
Hence, in the example above, the usage of yargs like:
yargs.positional('port', {
require: false,
describe: 'port to bind on',
default: 8080
})
is documented at:
https://github.com/yargs/yargs/blob/master/docs/api.md

I found the above answer a bit complicated and to help anyone who may land on this page in the future, I would recommend reading this GeeksForGeeks article:
https://www.geeksforgeeks.org/node-js-yargs-module/
The example with .command(cmd, desc, [builder], [handler]) is this:
//Add note
yargs
.command({
command: "add",
describe: "Add a note",
builder: {
title: {
describe: "Title of the note",
demandOption: true,
type: "string",
},
},
handler: (argv) => {
console.log("Added note with title:", argv.title);
},
})
.parse();
In the terminal, you have to type:
node app.js add --title="The Complete Node.js Developer Course (3rd Edition)"

Related

How do i fix DEPRECATION: The matcher factory for "toHaveBeenTriggeredOnAndWith"?

Can anyone tell me what needs to be changed this test?
it('Should update settings of bar', () => {
const newSettings = {
dataset: [
{
data: [{
name: 'Category A',
value: 373,
color: '#1D5F8A',
id: 1
}],
name: ''
}
]
};
barObj.updated(newSettings);
const dataLength = barObj.settings.dataset[0].data.length;
expect(dataLength).toEqual(1);
});
I am getting this error from Jasmine and if i follow the link https://jasmine.github.io/tutorials/upgrading_to_Jasmine_4.0#matchers-cet i dont see exactly what i would need to change?
ERROR: 'DEPRECATION: The matcher factory for "toHaveBeenTriggeredOnAndWith" accepts custom equality testers, but this parameter will no longer be passed in a future release. See https://jasmine.github.io/tutorials/upgrading_to_Jasmine_4.0#matchers-cet for details. (in spec: Bar API Should update settings of bar)
I also cant find a lot of information about this message. I also dont have any custom equality matchers in the system. https://jasmine.github.io/tutorials/custom_equality
Try to update karma-jasmine package. It helped me.
I had this problem using "#metahub/karma-jasmine-jquery". You can modify the bundle in place and remove the second parameter from the `` toHaveBeenTriggeredOnAndWith" function. Or copy the module somewhere, uninstall "#metahub/karma-jasmine-jquery" and install the modified module: npm install ./#metahub/karma-jasmine-jquery

In my Cypress.io tests why do I need to treat a cy.task like it is asyncronous when its not

I have Cypress.io tests that use a simple Cypress task to log some table information to the terminal. For example I have a test like so:
it("Writes some console logs and checks a val", () => {
cy.task("rowLog", { id: 1, name: "foo", type: "bar" });
let one = 1;
expect(one).to.equal(2);
});
And the task, "rowLog" like so:
module.exports = (on, config) => {
on("task", {
rowLog(data) {
// use node.js console.table to pretty print table data:
console.table(data);
return null;
},
}
But the result of rowLog will not display in my terminal if I run Cypress headlessly via Cypress run. This is because the test will fail. If we switch the test so that it passes, then it will show.
However I just realized that if I treat rowLog like it's async like below. It will print the results to the terminal:
it("Writes some console logs and checks a val", () => {
// add a .then to task:
cy.task("rowLog", { id: 1, name: "foo", type: "bar" }).then(() => {
let one = 1;
expect(one).to.equal(2);
});
});
This is not what I would expect from the docs. They say that:
cy.task() yields the value returned or resolved by the task event in the pluginsFile.
(source)
And that a task can yield either a promise or a value.
I'm new to Cypress here-- is there something I'm missing or doing wrong? I'd like to be able to not have to chain my tasks with .then statements if it is just synchronous stuff like writing output to ensure everything is emitted to my terminal.
If you look into the type definition of cy.task command, you will see that it returns a Chainable (that is a promise-like entity). So it behaves like any other cy command (ansynchrounously).
As for the yield either a promise or a **value** - this statement refers to the handler of the task, not the task itself. As for the other command, Cypress will wrap a returned value into a promise if it was not done by the handler.

GraphQL Nexus Schema (nexusjs) doesn't compile with scalar types

I am trying to follow the documentation on the Nexus-Schema (nexusjs) website for adding scalar types to my GraphQL application.
I have tried adding many of the different implementations to my src/types/Types.ts file using the samples provided in the documentation and the interactive examples. My attempts include:
Without a 3rd party libraries:
const DateScalar = scalarType({
name: 'Date',
asNexusMethod: 'date',
description: 'Date custom scalar type',
parseValue(value) {
return new Date(value)
},
serialize(value) {
return value.getTime()
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return new Date(ast.value)
}
return null
},
})
With graphql-iso-date 3rd party library:
import { GraphQLDate } from 'graphql-iso-date'
export const DateTime = GraphQLDate
With graphql-scalars 3rd party library (as shown in the ghost example):
export const GQLDate = decorateType(GraphQLDate, {
rootTyping: 'Date',
asNexusMethod: 'date',
})
I am using this new scalar type in an object definition like the following:
const SomeObject = objectType({
name: 'SomeObject',
definition(t) {
t.date('createdAt') // t.date() is supposed to be available because of `asNexusMethod`
},
})
In all cases, these types are exported from the types file and imported into the makeSchema's types property.
import * as types from './types/Types'
console.log("Found types", types)
export const apollo = new ApolloServer({
schema: makeSchema({
types,
...
context:()=>(
...
})
})
The console.log statement above does show that consts declared in the types file are in scope:
Found types {
GQLDate: Date,
...
}
If I run the app in development mode, everything boots up and runs fine.
ts-node-dev --transpile-only ./src/app.ts
However, I encounter errors whenever I try to compile the app to deploy to a server
ts-node ./src/app.ts && tsc
Note: This error occurs occurs running just ts-node ./src/app.ts before it gets to tsc
The errors that shown during the build process are the following:
/Users/user/checkouts/project/node_modules/ts-node/src/index.ts:500
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: тип Unable to compile TypeScript:
src/types/SomeObject.ts:11:7 - error TS2339: Property 'date' does not exist on type 'ObjectDefinitionBlock<"SomeObject">'.
11 t.date('createdAt')
Does anyone have any ideas on either:
a) How can I work around this error? While long-term solutions are ideal, temporary solutions would also be appreciated.
b) Any steps I could follow to debug this error? Or ideas on how get additional information to assist with debugging?
Any assistance would be very much welcomed. Thanks!
The issue seems to be resolved when --transpile-only flag is added to the nexus:reflect command.
This means the reflection command gets updated to:
ts-node --transpile-only ./src/app.ts
and the build comand gets updated to:
env-cmd -f ./config/.env ts-node --transpile-only ./src/app.ts --nexusTypegen && tsc
A github issue has also been created which can be reviewed here: https://github.com/graphql-nexus/schema/issues/690

WebdriverIO waitUntil example is not working

I am trying to use Webdriverio v5 and I have problems to run the example for waitUntil https://webdriver.io/docs/api/browser/waitUntil.html
it('should wait until text has changed', () => {
browser.waitUntil(() => {
return $('#someText').getText() === 'I am now different'
}, 5000, 'expected text to be different after 5s');
});
the error is saying
Type 'boolean' is not assignable to type 'Promise<boolean>'
anyone else is facing the same problem?
or how to fix it?
while in v4 everything works as expected
It looks like you're using typescript in your tests. Make sure you've gone through the entire typescript/webdriverio setup: https://webdriver.io/docs/typescript.html
In this case, I think you need to add wdio-sync to your compilerOptions types setting.
"compilerOptions": {
"types": ["node", "#wdio/sync"]
}

how to configure gulp-mocha with the following mocha.opts configuration?

I am trying to run mocha with gulp with the configuration existed before.
moch.opts has the following line.
--timeout 999999
--ui tdd
--full-trace
--recursive
--compilers js:babel-register
how to add them here :
gulp.task('test', function() {
return gulp.src('sampleTest/*.js', { read: false })
.pipe(mocha());
});
I believe you can either create properties on the options object passed to gulp-mocha or you can just have it read the options file. In my case, I didn't want to duplicate things like --recursive or --require test/_init.js, but I did want to override the reporter, so I use the code shown below:
gulp.task('test', ['compile'], function() {
return gulp.src([], { read: false })
.pipe(mocha({
opts: 'test/mocha.opts',
reporter: 'min'
}))
.on('error', gutil.log);
});
You may want to modify this so that it doesn't assume the default path to test files (e.g. test/*.js), but in my simple case I didn't even need to pass a path to mocha. I'm just using gulp to trigger it (as if I had run on the command line something like mocha --opts test/mocha.opts --reporter min)
Options are passed directly to the mocha binary, so you can use any its command-line options in a camelCased form. this is the document link
gulp.task('test', ['compile'], function() {
return gulp.src([], { read: false })
.pipe(mocha({
timeout: 999999,
fullTrace: true,
reporter: 'min'
}))
.on('error', gutil.log);
});
add the setTimeout call after the mocha call
.pipe(mocha(),setTimeout(function() {
}, 999999))

Resources