Skip to content

Instantly share code, notes, and snippets.

@cyberhck
Created November 25, 2018 03:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyberhck/40c2eae9763f141c7624d96d7e91349a to your computer and use it in GitHub Desktop.
Save cyberhck/40c2eae9763f141c7624d96d7e91349a to your computer and use it in GitHub Desktop.
matcher for typestyle's style
import ToHaveTypeStyleMatcher from "./ToHaveTypeStyleMatcher";
describe("ToHaveTypeStyleMatcher", () => {
it("compare returns an object containing message and pass key", () => {
const prop = jest.fn(() => "TS-0000");
const typestyleErrorMessageSnip = "TypeStyle does not match with actual, instead found";
expect(typeof (ToHaveTypeStyleMatcher as any).toHaveTypeStyle().compare({prop}) === "object").toBeTruthy();
const compare = (ToHaveTypeStyleMatcher as any).toHaveTypeStyle().compare({prop});
expect(compare.message).toBeDefined();
expect(compare.pass).toBeDefined();
expect(compare.message().indexOf(typestyleErrorMessageSnip)).not.toBe(-1);
});
});
import * as Enzyme from "enzyme";
import "jest-enzyme";
import {NestedCSSProperties} from "typestyle/lib/types";
import {hash, isSubset} from "./Utils";
const map = {};
const mock = jest.fn((...args) => {
args = args.length === 1 ? args[0] : args;
const rand = Math.abs(hash(JSON.stringify(args)));
map[rand] = args;
return `TS-${rand}`;
});
const mockExtends = (...objects: (NestedCSSProperties | undefined | null)[]) => {
let result: NestedCSSProperties = {};
for (const object of objects) {
result = {...result, ...object};
}
return result;
};
jest.mock("typestyle", () => ({
classes: (...classNames) => classNames.join(" ").trim(),
extend: mockExtends,
media: () => 0,
style: mock
}));
declare global {
namespace jest {
// tslint:disable-next-line:interface-name
interface Matchers<R> {
toHaveTypeStyle: (style: NestedCSSProperties) => void;
}
}
}
const ToHaveTypeStyleMatcher: jasmine.CustomMatcherFactories = {
toHaveTypeStyle: () => {
return {
compare: (component: Enzyme.ReactWrapper<null, null>, expected: NestedCSSProperties) => {
const classList: string[] = component.prop<string>("className").match(/TS-[0-9]+/g);
let matched: boolean = false;
const allClassNames = [];
for (const className of classList) {
allClassNames.push(map[className.split("-")[1]]);
const properties = map[className.split("-")[1]];
if (properties instanceof Array) {
properties.forEach((property) => {
if (isSubset(property, expected)) {
matched = true;
}
});
} else if (isSubset(properties, expected)) {
matched = true;
break;
}
}
return {
message: () => {
return `TypeStyle does not match with actual, instead found \n` +
`${JSON.stringify(allClassNames, null, 2)}, \n` +
`expected \n` +
JSON.stringify(expected, null, 2);
},
pass: matched
};
}
};
}
};
export default ToHaveTypeStyleMatcher;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment