ExtensibleFunction.test.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. /* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */
  20. import { ExtensibleFunction } from '@superset-ui/core';
  21. describe('ExtensibleFunction', () => {
  22. interface Func1 {
  23. (): number;
  24. }
  25. class Func1 extends ExtensibleFunction {
  26. constructor(x: unknown) {
  27. super(() => x); // closure
  28. }
  29. }
  30. interface Func2 {
  31. (): number;
  32. }
  33. class Func2 extends ExtensibleFunction {
  34. x: unknown;
  35. constructor(x: unknown) {
  36. super(() => this.x); // arrow function, refer to its own field
  37. this.x = x;
  38. }
  39. // eslint-disable-next-line class-methods-use-this
  40. hi() {
  41. return 'hi';
  42. }
  43. }
  44. class Func3 extends ExtensibleFunction {
  45. x: unknown;
  46. constructor(x: unknown) {
  47. // @ts-ignore
  48. super(function customName() {
  49. // @ts-ignore
  50. return customName.x;
  51. }); // named function
  52. this.x = x;
  53. }
  54. }
  55. it('its subclass is an instance of Function', () => {
  56. expect(Func1).toBeInstanceOf(Function);
  57. expect(Func2).toBeInstanceOf(Function);
  58. expect(Func3).toBeInstanceOf(Function);
  59. });
  60. const func1 = new Func1(100);
  61. const func2 = new Func2(100);
  62. const func3 = new Func3(100);
  63. it('an instance of its subclass is executable like regular function', () => {
  64. expect(func1()).toEqual(100);
  65. expect(func2()).toEqual(100);
  66. });
  67. it('its subclass behaves like regular class with its own fields and functions', () => {
  68. expect(func2.x).toEqual(100);
  69. expect(func2.hi()).toEqual('hi');
  70. });
  71. it('its subclass can set name by passing named function to its constructor', () => {
  72. expect(func3.name).toEqual('customName');
  73. });
  74. });