skovhus / jest-codemods Goto Github PK
View Code? Open in Web Editor NEWCodemods for migrating to Jest https://github.com/facebook/jest ๐พ
License: MIT License
Codemods for migrating to Jest https://github.com/facebook/jest ๐พ
License: MIT License
Please add support to migrate the sinon to jest.
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()
}
}
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);
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!
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;
});
The chai-should codemod produces a bad result when chaining property
with a
/an
. See this diff produced:
expect( state )
- .to.have.property( 'example.wordpress.com' )
- .to.be.a( 'object' );
+ .expect( typeof state ).toBe( 'object' );
See failing tests with proposed codemod result in #92
Detected in Automattic/wp-calypso#19631 by @gziolo
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.
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?
Jest is taking over https://www.npmjs.com/package/expect in an upcoming release. As part of this a codemod was developed (#39) and Jest browser support was added for jest-matchers
(will be expect@21+
) and other relevant packages (jestjs/jest#3360).
Background:
Before releasing this:
expect
package and document browser supportFYI @cpojer
@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
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
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']));
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(/^
It should be possible to transform Proxyquire mocks to Jest mocks.
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 transformer converts the test
methods to it
. However the latest Jest docs advertise the usage of test
instead of it
: http://facebook.github.io/jest/docs/en/api.html#testname-fn
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.
Would you accept a PR that adds the possibility to specify the transformer, something like:
jest-codemods path -f -t=mocha
?
The codemod can sometimes eat valuable comments like /* eslint: ... */
. It shouldn't do that.
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. : )
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.
test.beforeEach(t => {
t.context.fn = () => 'foo';
});
test('will execute foo', t => {
t.is(t.context.fn(), 'foo');
});
The t.is
will be modified, but the t.context will be left in place and cause errors. Perhaps renaming and moving to the file closure would work.
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?
I would love a codemod to help transition from https://github.com/hapijs/lab and https://github.com/hapijs/code. I'd be happy to look into doing it myself when I get the time, but I just wanted an issue out here for tracking if you don't mind.
AVA can pass a message to the snapshot, so does expect, it would be nice if the codemod retained that.
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);
});
Currently the async keyword might be lost in the transformation. Ensure that this doesn't happen...
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:
tick
functions doesn't seem compatible with Jest)Example of a project using Sinon: WordPress/gutenberg#1788 (comment)
This line:
foo.should.be.true()
is transformed into:
expect(foo).toBe(true)();
but should be
expect(foo).toBe(true);
PS: As a dirty workaround I just replace )();
with );
jest-codemods/src/transformers/chai-should.test.js
Lines 545 to 558 in e3a3f66
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
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);
}
});
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);
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.
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..
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).
Hi,
It would be nice to take into account the aliases for every functions that are map in the transformer for Expect.
Ex: https://github.com/mjackson/expect#toinclude
I don't know if there would be some collision problems because of the same function name present but with different behavior.
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);
โฆ
});
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.
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?
jestjs/jest#2133 this will hopefully land soon, and that means t.plan
will be supported as expect.assertions
$ 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
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
Unsupported, make warning
Remap
Investigate
Finalize
it
or test
- t.deepEqual(
- embed,
- omit(validatedEmbeds[index], 'validation'),
- 'does not modify the rest of embed ' + index
- );
+ expect(embed).toEqual(omit(validatedEmbeds[index], 'validation'));
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
Recently Chai should (https://github.com/chaijs/chai) transformation was added. The semantics is very close to should.js (https://github.com/tj/should.js/), so we can make official support for transforming should.js assertions to Jest.
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
Love your tool! To make it even more friendly; Can you please change the message: "ERROR: Git directory is not clean. Refusing to continue." ?
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()
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.