jest-codemods icon indicating copy to clipboard operation
jest-codemods copied to clipboard

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

Open WebDevMichael opened this issue 7 years ago • 7 comments

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']));

WebDevMichael avatar Jun 28 '17 15:06 WebDevMichael

Thanks for reporting this. : )

Do you want to work on a PR for this?

skovhus avatar Jun 28 '17 16:06 skovhus

Yes I would like to give it a try 😉

WebDevMichael avatar Jun 28 '17 16:06 WebDevMichael

Sound good. Let me know if you need any help. : )

skovhus avatar Jun 28 '17 17:06 skovhus

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

WebDevMichael avatar Jun 28 '17 21:06 WebDevMichael

It sounds right to me.

skovhus avatar Jun 29 '17 06:06 skovhus

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.

WebDevMichael avatar Jun 29 '17 10:06 WebDevMichael

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.

skovhus avatar Jun 29 '17 10:06 skovhus