hooks.spec.ts 2.70 KiB
import { hookAfter, hookBefore, hookFinally } from './hooks';
type Callback = (x: string) => void;
describe('hooksBefore', () => {
  it('should execute the hook before the original method', () => {
    class TestClass {
      public foo(f: Callback): void {
        f('bar');
    hookBefore(TestClass.prototype, 'foo', (f: Callback) => f('before'));
    const instance = new TestClass();
    const callback = jasmine.createSpy('callback');
    instance.foo(callback);
    expect(callback).toHaveBeenCalledTimes(2);
    expect(callback.calls.first().args).toEqual(['before']);
    expect(callback.calls.mostRecent().args).toEqual(['bar']);
  });
});
describe('hookAfter', () => {
  it('should execute the hook after the original method', () => {
    class TestClass {
      public foo(f: Callback): void {
        f('bar');
    hookAfter(TestClass.prototype, 'foo', (f: Callback) => f('after'));
    const instance = new TestClass();
    const callback = jasmine.createSpy('callback');
    instance.foo(callback);
    expect(callback).toHaveBeenCalledTimes(2);
    expect(callback.calls.first().args).toEqual(['bar']);
    expect(callback.calls.mostRecent().args).toEqual(['after']);
  });
  it('should not execute the hook when the original method throws', () => {
    const err = new Error('foo');
    class TestClass {
      public foo(f: Callback): void {
        throw err;
    hookAfter(TestClass.prototype, 'foo', (f: Callback) => f('after'));
    const instance = new TestClass();
    const callback = jasmine.createSpy('callback');
    expect(() => instance.foo(callback)).toThrow(err);
    expect(callback).not.toHaveBeenCalled();
  });
});
describe('hookFinally', () => {
  it('should execute the hook after the original method', () => {
    class TestClass {
      public foo(f: Callback): void {
        f('bar');
7172737475767778798081828384858687888990919293949596979899100101102103104105
} } hookFinally(TestClass.prototype, 'foo', (f: Callback) => f('finally')); const instance = new TestClass(); const callback = jasmine.createSpy('callback'); instance.foo(callback); expect(callback).toHaveBeenCalledTimes(2); expect(callback.calls.first().args).toEqual(['bar']); expect(callback.calls.mostRecent().args).toEqual(['finally']); }); it('should execute the hook even if the original method throws', () => { const err = new Error('foo'); class TestClass { public foo(f: Callback): void { throw err; } } hookFinally(TestClass.prototype, 'foo', (f: Callback) => f('finally')); const instance = new TestClass(); const callback = jasmine.createSpy('callback'); expect(() => instance.foo(callback)).toThrow(err); expect(callback).toHaveBeenCalledWith('finally'); }); });