Coder Social home page Coder Social logo

skovhus / jest-codemods Goto Github PK

View Code? Open in Web Editor NEW
868.0 8.0 82.0 2.18 MB

Codemods for migrating to Jest https://github.com/facebook/jest 👾

License: MIT License

JavaScript 2.55% TypeScript 97.31% Shell 0.14%
codemod jscodeshift mocha ava jest tape testing chai codemods jest-codemods

jest-codemods's Introduction

jest-codemods 👾

Codemods that simplify migrating JavaScript and TypeScript test files from AVA, Chai, Expect.js (by Automattic), [email protected] (by mjackson), Jasmine, Mocha, proxyquire, Should.js, Tape, Sinon, and Node-Tap to Jest.

Build Status version downloads Code Coverage MIT License PRs Welcome Tweet

Codemods are small programs that help you automate changes to your codebase. Think of them as search and replace on steroids.

We made jest-codemods so you can try out Jest on your existing codebase. We strive to make the migration as smooth as possible, but some manual intervention and tweaks to your tests are to be expected.

Usage (CLI)

To use the interactive CLI run

$ npx jest-codemods

If you do not have npx installed, you can install the jest-codemods command globally by running npm install -g jest-codemods.

For more options

$ npx jest-codemods --help

    Usage:      npx jest-codemods <path> [options]

    Examples:   npx jest-codemods src
                npx jest-codemods src/**/*.test.js

    Options:
      -f, --force       Bypass Git safety checks and force codemods to run
      -d, --dry         Dry run (no changes are made to files)

To transform all test files in a directory run jest-codemods . in your terminal.

Notice the console output for errors, manual intervention and tweaks might be required.

Usage (jscodeshift)

To make the process as simple as possible, we recommend the jest-codemods CLI that wraps the jscodeshift executable. But you can also run the transformations directly using jscodeshift.

$ npm install -g jscodeshift
$ npm install jest-codemods
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/ava.js test-folder
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/chai-assert.js test-folder
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/chai-should.js test-folder
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/expect-js.js test-folder
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/expect.js test-folder
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/jasmine-globals.js test-folder
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/jasmine-this.js test-folder
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/mocha.js test-folder
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/should.js test-folder
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/tape.js test-folder
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/sinon.js test-folder
$ jscodeshift -t node_modules/jest-codemods/dist/transformers/jest-globals-import.js test-folder

Test environment: Jest on Node.js or other

If you're using Jest as your test runner and executing tests on Node.js, you'll want to use the default option when prompted. In this case, jest-codemods assumes that global values such as expect and jest are provided and will not require() them explicitly.

If, however, you are using a different test runner or executing Jest tests in a browser, you may need to choose the option with explicit require() calls.

In the second case, after running jest-codemods, you might need to install a few dependencies:

yarn add --dev expect jest-mock

npm install --save-dev expect jest-mock

pnpm install --save-dev expect jest-mock

Transformations

If possible import / require statements determine if any transformation are carried out. The original code quoting style is preserved. Warnings are made if packages are used that are incompatible with Jest.

Inspiration

Thanks to avajs/ava-codemods for inspiration and original CLI setup.

The Mocha and Chai assert support began its life at paularmstrong/mocha-to-jest-codemod.

Chai Should/Expect came from AlexJuarez/chai-to-jasmine.

Links

Contributing

To get started, run:

pnpm install

When developing:

pnpm verify  # (build/lint/test)
pnpm build
pnpm lint
pnpm test
pnpm test:cov
pnpm test:watch

License

MIT

jest-codemods's People

Contributors

ahutchings avatar avaly avatar bcmarinacci avatar cameronhunter avatar catc avatar coleturner avatar danbeam avatar dependabot[bot] avatar jhilker avatar josh-degraw avatar jungomi avatar kristerkari avatar leko avatar lhorie avatar macklinu avatar matthewtrout avatar merceyz avatar milahu avatar mjomble avatar mxmul avatar paularmstrong avatar renovate-bot avatar renovate[bot] avatar seansfkelley avatar sejoker avatar sgilroy avatar skovhus avatar skovy avatar wmertens avatar wshowair avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jest-codemods's Issues

Unexpected conversion of .Ok to .toBeTruthy()

This is a little weird, but in a repo I was converting there are some constants that are defined like:

const MESSAGES = {
  Ok: 'x',
  Cancel: 'y',
};

And one of the codemods (I think the chai one) replaced MESSAGES.Ok with MESSAGES.toBeTruthy().

Check if git directory is clean upfront.

Love your tool! To make it even more friendly; Can you please change the message: "ERROR: Git directory is not clean. Refusing to continue." ?

  • Please show this message before asking what to migrate. Saves time and frustration.
  • Because you ask it upfront, it does not have to be this aggressive error but it could be something like: "Thank you for using jest-codemods! But before we continue, please stash your git changes."

Issue with AVA codemod

Out of 21 tests I got this error 3 times:

peError: Cannot read property 'type' of undefined
    at getIdentifierFromExpression (/Users/jamuferguson/dev/paypal/p2pnodeweb/node_modules/jest-codemods/dist/utils/recast-helpers.js:17:13)
    at getIdentifierFromExpression (/Users/jamuferguson/dev/paypal/p2pnodeweb/node_modules/jest-codemods/dist/utils/recast-helpers.js:20:12)
    at getIdentifierFromExpression (/Users/jamuferguson/dev/paypal/p2pnodeweb/node_modules/jest-codemods/dist/utils/recast-helpers.js:20:12)
    at /Users/jamuferguson/dev/paypal/p2pnodeweb/node_modules/jest-codemods/dist/transformers/ava.js:163:79
    at Array.filter (native)
    at Collection.filter (/Users/jamuferguson/dev/paypal/p2pnodeweb/node_modules/jscodeshift/dist/Collection.js:60:46)
    at rewriteTestCallExpression (/Users/jamuferguson/dev/paypal/p2pnodeweb/node_modules/jest-codemods/dist/transformers/ava.js:162:12)
    at /Users/jamuferguson/dev/paypal/p2pnodeweb/node_modules/jest-codemods/dist/transformers/ava.js:173:29
    at Array.forEach (native)
    at avaToJest (/Users/jamuferguson/dev/paypal/p2pnodeweb/node_modules/jest-codemods/dist/transformers/ava.js:173:16)

It's confused by this fairly confusing code (simplified here of course):

import test from 'ava'

test('should pass', t => {
    return shouldFail(t, 'hi')
})

function shouldFail(t, message) {
    return Promise.reject().catch(err => {
        t.same(err.message, message)
    })
}

Mocha: done to promise transform

In mocha it is possible to write this:

beforeAll((done) => {
  done();
});

Jasmine requires a promise to be returned. Is it possible to rewrite this to the following:

beforeAll(() => {
  let promise = new Promise((resolve, reject) => {
    resolve();
  });
  return promise;
});

Tape: how to replace t.test and t.skip

Our codebase has quite a few of those, but now that's the only warning left, except sinon ( #68 )

An example test with those looks like:

'use strict';

var algoliasearchHelper = require('../../../index');

var _ = require('lodash');

var fakeClient = {
  addAlgoliaAgent: function() {}
};

test('helper.hasRefinements(attribute)', function() {
  var helper;

  // cannot be tested since there's no way to know that a numeric refinement
  // was once added then removed thus we always return false when not found
  t.skip('undefined attribute', function(tt) {
    setup();
    tt.throws(_.partial(helper.hasRefinements, 'unknown'), Error, 'it throws when unknown attribute');
    tt.end();
  });

  t.test('numericRefinement', function(tt) {
    tt.test('with refinement', function(ttt) {
      setup();
      helper.addNumericRefinement('price', '=', 1337);
      ttt.equal(helper.hasRefinements('price'), true);
      ttt.end();
    });

    tt.test('without refinement', function(ttt) {
      setup();
      helper.addNumericRefinement('price', '=', 1337);
      helper.clearRefinements('price');
      ttt.equal(helper.hasRefinements('price'), false);
      ttt.end();
    });
  });

  t.test('facet', function(tt) {
    tt.test('with refinement', function(ttt) {
      setup({
        facets: ['color']
      });
      helper.toggleFacetRefinement('color', 'red');
      ttt.equal(helper.hasRefinements('color'), true);
      ttt.end();
    });

    tt.test('without refinement', function(ttt) {
      setup({
        facets: ['color']
      });
      ttt.equal(helper.hasRefinements('color'), false);
      ttt.end();
    });
  });

  t.test('disjunctiveFacet', function(tt) {
    tt.test('with refinement', function(ttt) {
      setup({
        disjunctiveFacets: ['author']
      });
      helper.toggleFacetRefinement('author', 'John Spartan');
      ttt.equal(helper.hasRefinements('author'), true);
      ttt.end();
    });

    tt.test('without refinement', function(ttt) {
      setup({
        disjunctiveFacets: ['author']
      });
      ttt.equal(helper.hasRefinements('author'), false);
      ttt.end();
    });
  });

  t.test('hierarchicalFacet', function(tt) {
    tt.test('with refinement', function(ttt) {
      setup({
        hierarchicalFacets: [{
          name: 'category',
          attributes: ['category.lvl0', 'category.lvl1']
        }]
      });
      helper.toggleFacetRefinement('category', 'Action Movies > Max');
      ttt.equal(helper.hasRefinements('category'), true);
      ttt.end();
    });

    tt.test('without refinement', function(ttt) {
      setup({
        hierarchicalFacets: [{
          name: 'category',
          attributes: ['category.lvl0', 'category.lvl1']
        }]
      });
      ttt.equal(helper.hasRefinements('category'), false);
      ttt.end();
    });
  });

  function setup(params) {
    helper = algoliasearchHelper(fakeClient, 'index', params);
  }
});

Skipping the test file without any error

I am running jest-codemods src/app/page-components/login/forgot-password/*.spec.ts --force
but getting the result below without any transformation happening or helpful message

$ jest-codemods src/app/page-components/login/forgot-password/*.spec.ts --force
? Which test library would you like to migrate from? Jasmine: this usage
? Will you be using Jest on Node.js as your test runner? Yes, use the globals provided by Jest (recommend
ed)
WARNING: Git directory is not clean. Forcibly continuing.
Executing command: jscodeshift -t C:\Users\Sarah.Saad\AppData\Roaming\npm\node_modules\jest-codemods\dist
transformers\jasmine-this.js src/app/page-components/login/forgot-password/forgot-password.component.spec.
ts
Processing 1 files...
Spawning 1 workers...
Sending 1 files to free worker...
All done.
Results:
0 errors
0 unmodified
1 skipped
0 ok
Time elapsed: 1.041seconds

AVA to Jest codemod

TODO

Unsupported, make warning

  • chaining test.serial.only for hooks
  • test.todo(title)
  • test.failing([title], implementation)
  • t.plan

Remap

  • test.serial([title], implementation) remove serial (all tests are serial)
  • test.cb([title], implementation) remove cb (all tests are callback style by default)
  • test.only([title], implementation) fit
  • test.skip([title], implementation) xit
  • test.before([title], implementation)
  • test.after([title], implementation)
  • test.beforeEach([title], implementation)
  • test.afterEach([title], implementation)

Investigate

  • Test macros

Finalize

-        t.deepEqual(
-            embed,
-            omit(validatedEmbeds[index], 'validation'),
-            'does not modify the rest of embed ' + index
-        );
+        expect(embed).toEqual(omit(validatedEmbeds[index], 'validation'));

Should Syntax does not handle should.throws with a regex

This line:

should.throws(foo, /^Error: Description/);

is transformed into:

expect(foo).throws(/^Error: Description/);

but should be

expect(foo).toThrowError(/^Description/);

PS: As a dirty workaround I just replace ).throws(/^Error: with ).toThrowError(/^

Keep async keywords

Currently the async keyword might be lost in the transformation. Ensure that this doesn't happen...

Add codemode for importing sinon

I do not have time to write a PR but you might want to add something like this:

/**
 * A quick code mod to move from using a sinon global to using sinon 2.x with an import statement.
 */

// findImports, hasRequireOrImport stolen from
// https://github.com/skovhus/jest-codemods/blob/master/src/utils/imports.js

function findImports (j, ast, pkg) {
  return ast.find(j.ImportDeclaration, {
    source: {
      value: pkg
    }
  })
}
/**
 * Detects CommonJS and import statements for the given package.
 * @return true if import were found, else false
 */
function hasRequireOrImport (j, ast, pkg) {
  // const requires = findRequires(j, ast, pkg).size()
  const imports = findImports(j, ast, pkg).size()
  return imports > 0
}

function hasIdentifier (j, ast, name) {
  return ast.find(j.Identifier, {
    name
  }).size() > 0
}

module.exports = function (fileInfo, api) {
  const j = api.jscodeshift
  const ast = j(fileInfo.source)

  if (!hasRequireOrImport(j, ast, 'sinon') && hasIdentifier(j, ast, 'sinon')) {
    let imp = ast.find(j.ImportDeclaration, {})
    // console.log(imp)

    let node = imp.at(imp.size() - 1)

    const {statement} = j.template
    // const newNode = j.importDeclaration('sinon', 'sinon');
    node.insertAfter(statement`import sinon from 'sinon'`)

    return node.toSource()
  }
}

Mocha migration does not rename files

I would expect migration to make files "seen" by jest. I have tests in test/footest.js, but AFAIK jest expects test/foo.test.js.

jest-codemods

Processing 23 files...

All done.

jest

No tests found

Migrating from expect.js breaks assertions on exceptions

I was migrating a code base from Automattic's expect.js, and I noticed that my .withArgs-calls simply disappeared.

Here's a repo with a reproducible demo: https://github.com/selbekk/reproduce-jest-codemods-error

Now, I realize that you COULD write an inline function that would pass these arguments to the function, and that's what I've been doing manually now - but it shouldn't just remove this - at the very least it should warn that I need to fix some stuff manually. When searching through the code for this project, I didn't even find a mention of withArgs - even though it's in the documented API.

Sorry I can't fix this with a PR - I need to sit down and learn codemods and ASTs first, I guess =) But at least there's a reproducible demo you can hack away at!

Please let me know if there's anything I can do to help!

Mocha: before description removal

In mocha this is a valid before hook:

beforeEach('some initialization', () => {

});

In jasmine this fails with the error:

    TypeError: originalBodyFn.apply is not a function

      at Object.fn (node_modules/jest-jasmine2/build/jasmine-async.js:64:44)

I.e. transformer should remove descriptions from before/after hooks.

ava: Support test.todo

Just going from test.todo('this should be a test some day') to test('this should be a test some day') should be enough. As long as no implementation is provided, jest is happy

Transformation error with Ava

I'm getting this error with some of my test files (which are written using Ava):

Transformation error
Error: [] does not match field "arguments": [Expression | SpreadElement] of type CallExpression
    at add (~/static/node_modules/ast-types/lib/types.js:580:31)
    at ~/static/node_modules/ast-types/lib/types.js:593:21
    at Array.forEach (native)
    at Function.value [as callExpression] (~/static/node_modules/ast-types/lib/types.js:592:34)
    at NodePath.ast.find.forEach.p (~/static/node_modules/jest-codemods/dist/transformers/ava.js:122:34)
    at __paths.forEach (~/static/node_modules/jscodeshift/dist/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (~/static/node_modules/jscodeshift/dist/Collection.js:75:18)
    at updateAssertions (~/static/node_modules/jest-codemods/dist/transformers/ava.js:98:12)
    at transforms.forEach.t (~/static/node_modules/jest-codemods/dist/transformers/ava.js:179:29)
All done. 

How do I go about figuring out where the problem lies?

Upgrading from Expect 1.x without using Jest?

I have a project with a custom test engine that has been using 1.x versions of mjackson's expect package for a while.
I would like to upgrade to the new version of the expect package, but keep my existing test engine instead of switching over to Jest.

Is this something that the "[email protected] (by mjackson)" codemod in this repo is meant to support or is it more for people who intend to switch over to Jest?

Codemod this keyword usage

Newer versions of Jest doesn't support using this inside hooks (e.g. beforeEach). Instead variables defined outside the scope can achieve the same.

Although this project is mainly moving from other test runners and assertion libraries to Jest, we might be able to help people here...

Background jestjs/jest#3628 (comment)

FYI @thymikee

Mocha migration this.timeout and this.slow

Mocha allows configuration of test timeout and warning about test slowness. These functions are not migrated, causing runtime errors in jest:

describe('test', function() {
    this.timeout(10000);
    
});

assert.isFalse(foo) transformed to expect(foo).toBe()

I have example.js with the following:

const assert = require('chai').assert;

const foo = false;
assert.isFalse(foo);

After running jest-codemods example.js, it looks like this:

const foo = false;
expect(foo).toBe();

Where before no error would be thrown, after the change, Jest fails with this:

Error: expect(received).toBe(expected)

Expected value to be (using ===):
  undefined
Received:
  false

Ava's test.throws accepts Promise value

When Ava's test.throws is used with a Promise value, it cannot be transformed directly to a Jest .toThrowError call, since the latter does not support Promise values.

Any ideas on what can be done here? jestjs/jest#1377 looks like it might be related.

Transformation error: Where to add a parser/compiler for TypeScript

I am looking to migrate our tests from Jasmine to Jest. However, it's failing on the first step with the error below:

Transformation error SyntaxError: Unexpected token (22:8)

It's recommended to use ts-jest but is jest-codemods configurable to allow for this or add TypeScript transformation?

Support for Sinon

Currently we warn that usage of Sinon might be incompatible with Jest. But it would be nice just to convert it to usage Jest Mocks and Spies.

The good news: Mocking and spying should be fairly easy to map to Jest.

But I think the following cannot really be converted to Jest:

  • useFakeTimers (and the tick functions doesn't seem compatible with Jest)
  • fakeServer
  • useFakeXMLHttpRequest

Example of a project using Sinon: WordPress/gutenberg#1788 (comment)

Fails when proxyquire identifier used but not as a function

In my old tests, there are a lot of palces where proxyquire.noCallThru() is called (once per test usually), but this causes an exception in jest-codemods (switching from ava to jest).

ERR test/utils/zipPackageTest.js Transformation error
TypeError: Cannot read property '0' of undefined
  at NodePath.ast.find.forEach.p (/Users/ssorense/.nvm/versions/node/v7.0.0/lib/node_modules/jest-codemods/dist/utils/proxyquire.js:46:37)
  ...

I poked around the code a little bit and it seems that this happens because the proxyquire util expects the proxyquire variable to be used only as a function. In this case, it's not used as a function and so the util fails when i tries to get the function args that don't exist.

It's easy enough to workaround - just remove the function call from tests before running the codemod, but I though you guys would want to know it's breaking in this instance (and other people might be interested in the workaround).

Destructuring of t (for tape)

I wrote all my tests by destructuring the t parameter of tape test function:

test('Test stuff', ({plan, equal, end}) => {
    plan(1);
    ok(true);
    end();
});

This style doesn't work with this codemod, however, if you're interested, I'd gladly work on a PR!

Edit: After looking a bit at the source, the easiest way would be to first transform "my style" to the conventional one you expect. And this could go to the ava/tape helper file, since it seems that ava works the same way.

chai-assert conversions fail when using chai default export

The codemod is not able to transform calls like "chai.assert.equal(...)" to Jest assertions. I would expect that either this:

import { assert } from 'chai';

assert.equal(1, 1);

or this:

import chai from 'chai';

chai.assert.equal(1, 1);

to be transformed to this:

expect(1).toEqual(1);

but only the first is actually fixed.

Chai `.to.be.an('array')` conversion fails

Chai's BDD style allows checking for an array with expect(foo).to.be.an('array'). This is converted by jest-codemods into expect (typeof foo).toBe('array'). However, the resulting spec will fail because typeof for an array is "object".

Perhaps a better transform would be:

// input 
expect(foo).to.be.an('array');

// output
expect(Array.isArray(foo)).toBe(true);

Cannot npm install jest-codemods

$ npm install -g jest-codemods
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
/usr/local/lib
└── (empty)

npm ERR! Darwin 15.6.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "jest-codemods"
npm ERR! node v6.3.1
npm ERR! npm  v3.10.3
npm ERR! path /usr/local/lib/node_modules/jest-codemods/bin/jest-codemods.js
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall chmod

npm ERR! enoent ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/jest-codemods/bin/jest-codemods.js'
npm ERR! enoent ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/jest-codemods/bin/jest-codemods.js'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

Ava to Jest: "ReferenceError: before is not defined"

After running jest-codemods on my Ava tests, I'm seeing exceptions: "ReferenceError: before is not defined". The stack trace is pointing to where test.before was transformed to before. Should test.before be transformed to beforeAll?

Input

test.before(() => {
   sinon.stub(Date, 'now').returns(12345);
});

Output

before(() => {
   sinon.stub(Date, 'now').returns(12345);
});

Preserve comments

The codemod can sometimes eat valuable comments like /* eslint: ... */. It shouldn't do that.

Troubles converting from expect 1.x: Cannot read property 'name' of undefined

I have been doing some potentially naughty extending of Expect 1.x, and I have been commenting them out as I go, with plans to fix them after the codemod goes though, but I'm stuck with this perplexing error.

Code is in the jest branch here: https://github.com/erikras/redux-form/tree/jest

$ jest-codemods --parser flow --dry
? Which test library would you like to migrate from? [email protected] (by mjackson)
? Should the tests be able to run in a browser? The tests should run on node.js (recommended)
? On which files or directory should the codemods be applied? src,test/**/*.js
Executing command: jscodeshift -t /usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js src --dry --parser flow
Processing 211 files...
Spawning 7 workers...
Running in dry mode, no files will be written!
Sending 31 files to free worker...
Sending 31 files to free worker...
Sending 31 files to free worker...
Sending 31 files to free worker...
Sending 31 files to free worker...
Sending 31 files to free worker...
Sending 25 files to free worker...
 ERR src/__tests__/createFieldArrayProps.spec.js Transformation error
TypeError: Cannot read property 'name' of undefined
    at updateSpyProperty (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:250:63)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:288:13)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateSpies (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:285:12)
    at expectTransformer (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:293:5)
 ERR src/__tests__/values.spec.js Transformation error
Error: undefined does not match field "name": string of type Identifier
    at add (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:580:31)
    at /usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:593:21
    at Array.forEach (native)
    at Function.value [as identifier] (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:592:34)
    at updateSpyProperty (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:252:152)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:288:13)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateSpies (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:285:12)
 ERR src/__tests__/formValues.spec.js Transformation error
Error: undefined does not match field "name": string of type Identifier
    at add (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:580:31)
    at /usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:593:21
    at Array.forEach (native)
    at Function.value [as identifier] (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:592:34)
    at updateSpyProperty (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:252:152)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:288:13)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateSpies (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:285:12)
 ERR src/__tests__/FieldArray.spec.js Transformation error
Error: Unknown matcher "toHaveText" (JEST_MATCHER_TO_MAX_ARGS)
    at balanceMatcherNodeArguments (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:78:19)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:162:9)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateMatchers (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:102:8)
    at expectTransformer (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:292:5)
 ERR src/__tests__/generateValidator.spec.js Transformation error
Error: undefined does not match field "name": string of type Identifier
    at add (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:580:31)
    at /usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:593:21
    at Array.forEach (native)
    at Function.value [as identifier] (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:592:34)
    at updateSpyProperty (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:252:152)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:288:13)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateSpies (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:285:12)
 ERR src/__tests__/handleSubmit.spec.js Transformation error
Error: undefined does not match field "name": string of type Identifier
    at add (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:580:31)
    at /usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:593:21
    at Array.forEach (native)
    at Function.value [as identifier] (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:592:34)
    at updateSpyProperty (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:252:152)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:288:13)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateSpies (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:285:12)
 ERR src/__tests__/Field.spec.js Transformation error
Error: undefined does not match field "name": string of type Identifier
    at add (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:580:31)
    at /usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:593:21
    at Array.forEach (native)
    at Function.value [as identifier] (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:592:34)
    at updateSpyProperty (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:252:152)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:288:13)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateSpies (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:285:12)
 ERR src/__tests__/reduxForm.spec.js Transformation error
Error: Unknown matcher "toContainExactly" (JEST_MATCHER_TO_MAX_ARGS)
    at balanceMatcherNodeArguments (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:78:19)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:162:9)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateMatchers (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:102:8)
    at expectTransformer (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:292:5)
 ERR src/__tests__/Fields.spec.js Transformation error
Error: undefined does not match field "name": string of type Identifier
    at add (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:580:31)
    at /usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:593:21
    at Array.forEach (native)
    at Function.value [as identifier] (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:592:34)
    at updateSpyProperty (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:252:152)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:288:13)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateSpies (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:285:12)
 ERR src/__tests__/Form.spec.js Transformation error
Error: undefined does not match field "name": string of type Identifier
    at add (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:580:31)
    at /usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:593:21
    at Array.forEach (native)
    at Function.value [as identifier] (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:592:34)
    at updateSpyProperty (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:252:152)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:288:13)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateSpies (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:285:12)
 ERR src/__tests__/FormSection.spec.js Transformation error
Error: undefined does not match field "name": string of type Identifier
    at add (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:580:31)
    at /usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:593:21
    at Array.forEach (native)
    at Function.value [as identifier] (/usr/local/lib/node_modules/jest-codemods/node_modules/recast/node_modules/ast-types/lib/types.js:592:34)
    at updateSpyProperty (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:252:152)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:288:13)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateSpies (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:285:12)
 ERR src/__tests__/actions.spec.js Transformation error
Error: Unknown matcher "toPass" (JEST_MATCHER_TO_MAX_ARGS)
    at balanceMatcherNodeArguments (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:78:19)
    at NodePath.ast.find.forEach.path (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:162:9)
    at __paths.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/usr/local/lib/node_modules/jest-codemods/node_modules/jscodeshift/src/Collection.js:75:18)
    at updateMatchers (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:102:8)
    at expectTransformer (/usr/local/lib/node_modules/jest-codemods/dist/transformers/expect.js:292:5)
All done.
Results:
12 errors
171 unmodified
0 skipped
28 ok
Time elapsed: 7.359seconds

Any help would be appreciated.

Should Syntax Parsing Error: Cannot read property 'name' of undefined

First of all, than you sooooo much for the Should Syntax implementation 😁

I'm using jest-codemods v0.9.1 and I have the following error:

TypeError: Cannot read property 'name' of undefined
    at NodePath.root.find.filter.replaceWith.p (/v6.5.0/lib/node_modules/jest-codemods/dist/transformers/chai-should.js:143:59)
    at NodePath.<anonymous> (/v6.5.0/lib/node_modules/jest-codemods/node_modules/jscodeshift/dist/collections/Node.js:144:47)
    at __paths.forEach (/v6.5.0/lib/node_modules/jest-codemods/node_modules/jscodeshift/dist/Collection.js:76:36)
    at Array.forEach (native)
    at Collection.forEach (/v6.5.0/lib/node_modules/jest-codemods/node_modules/jscodeshift/dist/Collection.js:75:18)
    at Collection.replaceWith (/v6.5.0/lib/node_modules/jest-codemods/node_modules/jscodeshift/dist/collections/Node.js:142:17)
    at Collection.typedMethod (/v6.5.0/lib/node_modules/jest-codemods/node_modules/jscodeshift/dist/Collection.js:376:43)
    at shouldIdentifierToExpect (/v6.5.0/lib/node_modules/jest-codemods/dist/transformers/chai-should.js:131:126)
    at transformer (/v6.5.0/lib/node_modules/jest-codemods/dist/transformers/chai-should.js:302:18)

With a console.log(calee) in file chai-should.js line 139:

Node {
  type: 'Identifier',
  start: 1929,
  end: 1935,
  loc:
   SourceLocation {
     start: Position { line: 71, column: 8 },
     end: Position { line: 71, column: 14 },
     lines: Lines {},
     indent: 8 },
  name: 'should',
  typeAnnotation: null }

Seems it's failing parsing this:

should(foo).be.undefined();

I just had to manually migrate those lines (by commenting + manual replace)..

expect(foo).toBeUndefined();

Everything else seems working fine..

Specify transformer

Would you accept a PR that adds the possibility to specify the transformer, something like:
jest-codemods path -f -t=mocha?

Chai `.to.have.all.keys()` conversion fails

In Chai when we want to assert that a JSON object has specific keys we can use .to.have.all.keys(). As you can see in the code below, the output is incorrect and the current output compares the complete JSON object to expect.arrayContaining()

const foo = { bar: true };
// input
expect(foo).to.have.all.keys('bar');

// current output
expect(foo).toEqual(expect.arrayContaining(['bar']));
// expected output
expect(Object.keys(foo)).toEqual(expect.arrayContaining(['bar']));

Chai plugins support

Chai plugins and chained assertions are not supported yet. They are really complex and we do log warnings when using them.

Not sure if it is worth fixing these. But might make sense to mention that chai can be used with Jest.

See https://ebaytech.berlin/into-the-great-unknown-migrating-from-mocha-to-jest-3baced083c7e

@pahund let me know if you have anything to add. Seems you overlooked the warnings for chained asserts... let me know if we can make them more clear. Thanks. : )

Mocha

@paularmstrong started integrating https://github.com/paularmstrong/mocha-to-jest-codemod into jest-codemods. This adds transformation of Mocha and Chai asserts. Great stuff!

There are a few thing to be done

  • Integration (Paul is on it)
  • Update README + package.json
  • Update migration guide in the facebook/jest repo (jestjs/jest#2232)
  • keep track of things missing transformation (maybe as GitHub issues). Currently in README of mocha-to-jest-codemod
  • 🎉

chai.assert.approximately() arguments don't map to Jest's .toBeCloseTo()

The chai-assert codemods will rewrite this:

assert.approximately(x, 1, 0.1);
assert.closeTo(y, 25, 50);

as

expect(x).toBeCloseTo(1, 0.1);
expect(y).toBeCloseTo(25, 50);

Which is almost always going to break tests, because the third argument in Chai's "approximately" is a delta whereas the second argument to Jest's "toBeCloseTo" is number of matching digits.

A more correct codemod output would probably be something like:

expect(Math.abs(x - 1)).toBeLessThan(0.1);
expect(Math.abs(y - 25)).toBeLessThan(50);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.