question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

typescript alias options not parsing off CommandModule in jest

See original GitHub issue

I’m trying to test some modules of yargs and noticed in my jest tests that yargs didn’t seem to be processing aliases on options like I expected. Below I expect the option ‘flag’ to end up making argv entries ‘flag’ and ‘f’, the alias. Instead it seems to not process the flag on my builder. How can I ensure my CommandModule tests work with alias options? PS is this the best way to drive this code path?

mkdir tmp/
cd tmp/
npm init -y
npm install jest typescript yargs ts-jest

jest.config.js

module.exports = {
	  transform: {'^.+\\.ts?$': 'ts-jest'},
	  testEnvironment: 'node',
	  testRegex: '.*\\.(test|spec)?\\.(ts|tsx)$',
	  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};

yargs.test.ts

import yargs = require('yargs');
import { Arguments, CommandModule } from 'yargs';
const spyConsole = jest.spyOn(console, 'log').mockImplementation();

interface MyArgs extends Arguments {
  flag: string;
  f?: string;
}

const flagCmd: CommandModule = {
  command: 'flag it',
  describe: 'flag a flag',
  builder: {
    flag: {
      type: 'boolean',
      description: 'Boolean Flag',
      alias: 'f',
      default: false,
    },
  },
  handler: async (argv: MyArgs) => {
    console.log(JSON.stringify(argv));
  },
};

it('parses an alias for the test', async () => {
  await flagCmd.handler(yargs(['-f']).command(flagCmd).parse());
  expect(spyConsole.mock.calls.length).toBe(1);
  expect(spyConsole.mock.calls[0][0]).toContain('"f":true');
  expect(spyConsole.mock.calls[0][0]).toContain('"flag":true');
});

node node_modules/jest/bin/jest.js yargs.test.ts
# returns a fail because the "flag":true key is missing.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:13 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
joekillercommented, Oct 16, 2020

With my newly discovered onFinishCommand this now works with the following:

import * as yargs from 'yargs';
import { Arguments, CommandModule } from 'yargs';
const spyConsole = jest.spyOn(console, 'log').mockImplementation();

interface MyArgs extends Arguments {
  flag: string;
  f?: string;
}

const flagCmd: CommandModule = {
  command: 'flag',
  describe: 'flag a flag',
  builder: {
    flag: {
      type: 'boolean',
      description: 'Boolean Flag',
      alias: 'f',
      default: false,
    },
  },
  handler: async (argv: MyArgs) => {
    console.log(JSON.stringify(argv));
    return Promise.resolve(argv);
  },
};

it('parses an alias for the test', async (done) => {
  await new Promise((resolve, reject) => {
    try {
      yargs
        .command(flagCmd)
        .onFinishCommand(async (r) => resolve(r))
        .exitProcess(false)
        .parse('flag -f');
    } catch (e) {
      reject(e);
    }
  });
  expect(spyConsole.mock.calls.length).toBe(1);
  expect(spyConsole.mock.calls[0][0]).toContain('"f":true');
  expect(spyConsole.mock.calls[0][0]).toContain('"flag":true');
  done();
});

1reaction
jltwheelercommented, Dec 10, 2020

Thanks @joekiller! So this method works perfectly with testing your command error handling in jest!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Node / Express Aliases with Jest - typescript - Stack Overflow
So it's clearly something with the aliases. And only when running Jest as everything works fine locally in development when I run the...
Read more >
Configuring Module Resolution On Typescript and Jest
The primary objective of this guide is to explain handling Module Aliases on Typescript and Jest. TL;DR — Here is a boilerplate project...
Read more >
Configuring Jest
Here is how to enable it globally (additional options are not supported):. JavaScript; TypeScript. /** @type {import('jest').Config} */
Read more >
TypeScript - Parcel
This means that some TypeScript features like const enum that require cross-file type information to compile will not work. To be warned about...
Read more >
serverless-bundle - npm
Advanced Options; TypeScript; Package Specific Config ... To use aliases in your tests you'll need to use Jest's moduleNameMapper .
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found