jest-codemods
jest-codemods copied to clipboard
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']));
Thanks for reporting this. : )
Do you want to work on a PR for this?
Yes I would like to give it a try 😉
Sound good. Let me know if you need any help. : )
src/transformers/chai-should.js:406
On this line node.type
equals Identifier
, the condition passes if node.type
equals ObjectExpression
. I want the if condition to pass so we can surround the constant with Object.keys
. Do you have a suggestion for this?
I already added tests in my fork: https://github.com/SpikeO/jest-codemods/commit/39dbb2228880914e3eba7a1ae94aa5ac91a9a14f
It sounds right to me.
How can I see if the Identifier (constant JSON object) is of the type ObjectExpression
?
Because Identifier can also be any other possible variable, i.e. an array.
So that is the challenging part.
Short answer: you can't.
Longer answer: if the identifier is assigned inside the file you can search the AST for assignment to this specific identifier... But it might be assigned multiple places. AND the identifier might be defined in another file.
I cases like this, I do a best guess and log a warning that the transformation might not be right.