Skip to content

Instantly share code, notes, and snippets.

@pahund
Last active April 20, 2022 04:35
Show Gist options
  • Save pahund/3abcc5212431cef3dae455d5285b7bd7 to your computer and use it in GitHub Desktop.
Save pahund/3abcc5212431cef3dae455d5285b7bd7 to your computer and use it in GitHub Desktop.
Using Chai and Jest assertions together with Jest's expect (thanks Ruben Oostinga!)
import chai from 'chai';
import sinonChai from 'sinon-chai';
import chaiAsPromised from 'chai-as-promised';
import chaiEnzyme from 'chai-enzyme';
chai.use(sinonChai);
chai.use(chaiAsPromised);
chai.use(chaiEnzyme());
// Make sure chai and jasmine ".not" play nice together
const originalNot = Object.getOwnPropertyDescriptor(chai.Assertion.prototype, 'not').get;
Object.defineProperty(chai.Assertion.prototype, 'not', {
get() {
Object.assign(this, this.assignedNot);
return originalNot.apply(this);
},
set(newNot) {
this.assignedNot = newNot;
return newNot;
}
});
// Combine both jest and chai matchers on expect
const jestExpect = global.expect;
global.expect = actual => {
const originalMatchers = jestExpect(actual);
const chaiMatchers = chai.expect(actual);
const combinedMatchers = Object.assign(chaiMatchers, originalMatchers);
return combinedMatchers;
};
@Darmikon
Copy link

You need also add a loop at the end of the file to copy additional static methods. Just fixed the bug today related to jest-styled-components.

Object.keys(jestExpect).forEach(
  key => (global.expect[key] = jestExpect[key])
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment