setup.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* global expect: false */
  2. import stringify from 'json-stable-stringify';
  3. import Lexer from "../src/Lexer";
  4. import ParseError from "../src/ParseError";
  5. import {
  6. Mode, ConsoleWarning,
  7. expectKaTeX, expectEquivalent,
  8. } from "./helpers";
  9. // Serializer support
  10. const typeFirstCompare = (a, b) => {
  11. if (a.key === 'type') {
  12. return -1;
  13. } else if (b.key === 'type') {
  14. return 1;
  15. } else {
  16. return a.key < b.key ? -1 : 1;
  17. }
  18. };
  19. const replacer = (key, value) => {
  20. if (value instanceof Lexer) {
  21. return {
  22. input: value.input,
  23. // omit value.settings
  24. lastIndex: value.tokenRegex.lastIndex,
  25. };
  26. } else {
  27. return value;
  28. }
  29. };
  30. const serializer = {
  31. print(val) {
  32. return stringify(val, {
  33. cmp: typeFirstCompare,
  34. space: ' ',
  35. replacer: replacer,
  36. });
  37. },
  38. test(val) {
  39. // Leave strings (e.g. XML) to other serializers
  40. return typeof val !== "string";
  41. },
  42. };
  43. expect.addSnapshotSerializer(serializer);
  44. // Mock console.warn to throw an error
  45. global.console.warn = x => { throw new ConsoleWarning(x); };
  46. // Expect extensions
  47. expect.extend({
  48. toParse(expr, settings) {
  49. return expectKaTeX(expr, settings, Mode.PARSE, this.isNot);
  50. },
  51. toFailWithParseError: function(expr, expected = ParseError) {
  52. return expectKaTeX(expr, undefined, Mode.PARSE, this.isNot, expected);
  53. },
  54. toBuild(expr, settings) {
  55. return expectKaTeX(expr, settings, Mode.BUILD, this.isNot);
  56. },
  57. toWarn(expr, settings) {
  58. return expectKaTeX(expr, settings, Mode.BUILD, this.isNot, ConsoleWarning);
  59. },
  60. toParseLike(expr, expected, settings) {
  61. return expectEquivalent(expr, expected, settings, Mode.PARSE, this.expand);
  62. },
  63. toBuildLike(expr, expected, settings) {
  64. return expectEquivalent(expr, expected, settings, Mode.BUILD, this.expand);
  65. },
  66. });