| 1 |
import { describe, expect, it, vi } from 'vitest'; |
| 2 |
|
| 3 |
import Swup, { Handler, HookName } from 'swup'; |
| 4 |
import BasePlugin from '../index'; |
| 5 |
|
| 6 |
declare module 'swup' { |
| 7 |
export interface HookDefinitions { |
| 8 |
test: undefined; |
| 9 |
} |
| 10 |
} |
| 11 |
|
| 12 |
describe('hooks', () => { |
| 13 |
it('should register and unregister hooks', () => { |
| 14 |
const handler = vi.fn(); |
| 15 |
const handlerOnce = vi.fn(); |
| 16 |
const handlerReplace = vi.fn(); |
| 17 |
const defaultHandler = vi.fn(); |
| 18 |
|
| 19 |
class Plugin extends BasePlugin { |
| 20 |
name = 'TestPlugin'; |
| 21 |
mount() { |
| 22 |
this.on('test', handler); |
| 23 |
this.once('test', handlerOnce); |
| 24 |
|
| 25 |
this.swup.hooks.callSync('test', undefined, defaultHandler); |
| 26 |
|
| 27 |
this.replace('test', handlerReplace); |
| 28 |
|
| 29 |
this.swup.hooks.callSync('test', undefined, defaultHandler); |
| 30 |
} |
| 31 |
unmount() { |
| 32 |
super.unmount(); |
| 33 |
this.swup.hooks.callSync('test'); |
| 34 |
this.swup.hooks.callSync('test'); |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
const swup = new Swup(); |
| 39 |
swup.hooks.create('test'); |
| 40 |
const plugin = new Plugin(); |
| 41 |
swup.use(plugin); |
| 42 |
swup.unuse(plugin); |
| 43 |
expect(handler).toHaveBeenCalledTimes(2); |
| 44 |
expect(handlerOnce).toHaveBeenCalledTimes(1); |
| 45 |
expect(handlerReplace).toHaveBeenCalledTimes(1); |
| 46 |
expect(defaultHandler).toHaveBeenCalledTimes(1); |
| 47 |
}); |
| 48 |
|
| 49 |
it('should bind hook handlers to plugin instance', () => { |
| 50 |
let thisArgUnbound: any; |
| 51 |
let thisArgBound: any; |
| 52 |
let thisArgArrow: any; |
| 53 |
|
| 54 |
const otherThis = {}; |
| 55 |
|
| 56 |
class Plugin extends BasePlugin { |
| 57 |
name = 'TestPlugin'; |
| 58 |
mount() { |
| 59 |
this.on('test', this.unbound); |
| 60 |
this.on('test', this.bound.bind(otherThis)); |
| 61 |
this.on('test', this.arrow); |
| 62 |
this.swup.hooks.callSync('test'); |
| 63 |
} |
| 64 |
unbound() { |
| 65 |
thisArgUnbound = this; |
| 66 |
} |
| 67 |
bound() { |
| 68 |
thisArgBound = this; |
| 69 |
} |
| 70 |
arrow = () => { |
| 71 |
thisArgArrow = this; |
| 72 |
}; |
| 73 |
} |
| 74 |
|
| 75 |
const swup = new Swup(); |
| 76 |
swup.hooks.create('test'); |
| 77 |
const plugin = new Plugin(); |
| 78 |
swup.use(plugin); |
| 79 |
expect(thisArgUnbound).toBe(plugin); |
| 80 |
expect(thisArgBound).toBe(otherThis); |
| 81 |
expect(thisArgArrow).toBe(plugin); |
| 82 |
}); |
| 83 |
}); |