Add generic types and update tests (#107)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add generic types and update tests * Add generic types to `on`, `off` and `emit` to enable some nicer TS usage if you specify what type you're expecting from the `EventData`. * Move the tests to be TypeScript source. This will help catch errors in the tests if there are any type errors. * Create a new test to test the generic types and make sure they pass and error when expected. * Upgrade to Mocha 8. * Did some tidying up of the package.json scripts. * Tweak TS setup to validate tests * Fix d.ts generation and tests
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Jason Miller <developit@users.noreply.github.com>
Diff stats
10 files+265 added−223 removed
- tests:+225 added−202 removed
- other:+40 added−21 removed
Provenance
- Commit
5116df4- Tree
93be70d- Author
Jack Franklin <jack@jackfranklin.net>- Committer
GitHub <noreply@github.com>- Parent
244cac2
10 files changed+265 added−223 removed
modified:src/index.ts+7 added-7 removed
123456567891011121314151616171819192021222313 unmodified lines373839404141424344456 unmodified lines525354555656575859608 unmodified lines6970717273737475767778export type EventType = string | symbol;
// An event handler can take an optional event argument// and should not return a valueexport type Handler = (event?: any) => void;export type WildcardHandler = (type: EventType, event?: any) => voidexport type Handler<T = any> = (event?: T) => void;export type WildcardHandler = (type: EventType, event?: any) => void;
// An array of all currently registered event handlers for a typeexport type EventHandlerList = Array<Handler>;export type WildCardEventHandlerList = Array<WildcardHandler>;
// A map of event types and their corresponding event handlers.export type EventHandlerMap = Map<EventType, EventHandlerList | WildCardEventHandlerList>;
export interface Emitter { on(type: EventType, handler: Handler): void; on<T = any>(type: EventType, handler: Handler<T>): void; on(type: '*', handler: WildcardHandler): void;
off(type: EventType, handler: Handler): void; off<T = any>(type: EventType, handler: Handler<T>): void; off(type: '*', handler: WildcardHandler): void;
emit<T = any>(type: EventType, event?: T): void; emit(type: '*', event?: any): void;13 unmodified lines * @param {string|symbol} type Type of event to listen for, or `"*"` for all events * @param {Function} handler Function to call in response to given event * @memberOf mitt */ on(type: EventType, handler: Handler) { on<T = any>(type: EventType, handler: Handler<T>) { const handlers = all.get(type); const added = handlers && handlers.push(handler); if (!added) { all.set(type, [handler]);6 unmodified lines * @param {string|symbol} type Type of event to unregister `handler` from, or `"*"` * @param {Function} handler Handler function to remove * @memberOf mitt */ off(type: EventType, handler: Handler) { off<T = any>(type: EventType, handler: Handler<T>) { const handlers = all.get(type); if (handlers) { handlers.splice(handlers.indexOf(handler) >>> 0, 1); }8 unmodified lines * @param {string|symbol} type The event type to invoke * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler * @memberOf mitt */ emit(type: EventType, evt: any) { emit<T = any>(type: EventType, evt: T) { ((all.get(type) || []) as EventHandlerList).slice().map((handler) => { handler(evt); }); ((all.get('*') || []) as WildCardEventHandlerList).slice().map((handler) => { handler(type, evt); }); } };}added:test/index_test.ts+182 added
1+import mitt, { Emitter } from '..';2+import chai, { expect } from 'chai';3+import { spy } from 'sinon';4+import sinonChai from 'sinon-chai';5+chai.use(sinonChai);6+7+describe('mitt', () => {8+ it('should default export be a function', () => {9+ expect(mitt).to.be.a('function');10+ });11+12+ it('should accept an optional event handler map', () => {13+ expect(() => mitt(new Map())).not.to.throw;14+ const map = new Map();15+ const a = spy();16+ const b = spy();17+ map.set('foo', [a, b]);18+ const events = mitt(map);19+ events.emit('foo');20+ expect(a).to.have.been.calledOnce;21+ expect(b).to.have.been.calledOnce;22+ });23+});24+25+describe('mitt#', () => {26+ let events, inst: Emitter;27+28+ beforeEach( () => {29+ events = new Map();30+ inst = mitt(events);31+ });32+33+ describe('on()', () => {34+ it('should be a function', () => {35+ expect(inst)36+ .to.have.property('on')37+ .that.is.a('function');38+ });39+40+ it('should register handler for new type', () => {41+ const foo = () => {};42+ inst.on('foo', foo);43+44+ expect(events.get('foo')).to.deep.equal([foo]);45+ });46+47+ it('should register handlers for any type strings', () => {48+ const foo = () => {};49+ inst.on('constructor', foo);50+51+ expect(events.get('constructor')).to.deep.equal([foo]);52+ });53+54+ it('should append handler for existing type', () => {55+ const foo = () => {};56+ const bar = () => {};57+ inst.on('foo', foo);58+ inst.on('foo', bar);59+60+ expect(events.get('foo')).to.deep.equal([foo, bar]);61+ });62+63+ it('should NOT normalize case', () => {64+ const foo = () => {};65+ inst.on('FOO', foo);66+ inst.on('Bar', foo);67+ inst.on('baz:baT!', foo);68+69+ expect(events.get('FOO')).to.deep.equal([foo]);70+ expect(events.has('foo')).to.equal(false);71+ expect(events.get('Bar')).to.deep.equal([foo]);72+ expect(events.has('bar')).to.equal(false);73+ expect(events.get('baz:baT!')).to.deep.equal([foo]);74+ });75+76+ it('can take symbols for event types', () => {77+ const foo = () => {};78+ const eventType = Symbol('eventType');79+ inst.on(eventType, foo);80+ expect(events.get(eventType)).to.deep.equal([foo]);81+ });82+83+ // Adding the same listener multiple times should register it multiple times.84+ // See https://nodejs.org/api/events.html#events_emitter_on_eventname_listener85+ it('should add duplicate listeners', () => {86+ const foo = () => {};87+ inst.on('foo', foo);88+ inst.on('foo', foo);89+ expect(events.get('foo')).to.deep.equal([foo, foo]);90+ });91+ });92+93+ describe('off()', () => {94+ it('should be a function', () => {95+ expect(inst)96+ .to.have.property('off')97+ .that.is.a('function');98+ });99+100+ it('should remove handler for type', () => {101+ const foo = () => {};102+ inst.on('foo', foo);103+ inst.off('foo', foo);104+105+ expect(events.get('foo')).to.be.empty;106+ });107+108+ it('should NOT normalize case', () => {109+ const foo = () => {};110+ inst.on('FOO', foo);111+ inst.on('Bar', foo);112+ inst.on('baz:bat!', foo);113+114+ inst.off('FOO', foo);115+ inst.off('Bar', foo);116+ inst.off('baz:baT!', foo);117+118+ expect(events.get('FOO')).to.be.empty;119+ expect(events.has('foo')).to.equal(false);120+ expect(events.get('Bar')).to.be.empty;121+ expect(events.has('bar')).to.equal(false);122+ expect(events.get('baz:bat!')).to.have.lengthOf(1);123+ });124+125+ it('should remove only the first matching listener', () => {126+ const foo = () => {};127+ inst.on('foo', foo);128+ inst.on('foo', foo);129+ inst.off('foo', foo);130+ expect(events.get('foo')).to.deep.equal([foo]);131+ inst.off('foo', foo);132+ expect(events.get('foo')).to.deep.equal([]);133+ });134+ });135+136+ describe('emit()', () => {137+ it('should be a function', () => {138+ expect(inst)139+ .to.have.property('emit')140+ .that.is.a('function');141+ });142+143+ it('should invoke handler for type', () => {144+ const event = { a: 'b' };145+146+ inst.on('foo', (one, two?) => {147+ expect(one).to.deep.equal(event);148+ expect(two).to.be.an('undefined');149+ });150+151+ inst.emit('foo', event);152+ });153+154+ it('should NOT ignore case', () => {155+ const onFoo = spy(),156+ onFOO = spy();157+ events.set('Foo', [onFoo]);158+ events.set('FOO', [onFOO]);159+160+ inst.emit('Foo', 'Foo arg');161+ inst.emit('FOO', 'FOO arg');162+163+ expect(onFoo).to.have.been.calledOnce.and.calledWith('Foo arg');164+ expect(onFOO).to.have.been.calledOnce.and.calledWith('FOO arg');165+ });166+167+ it('should invoke * handlers', () => {168+ const star = spy(),169+ ea = { a: 'a' },170+ eb = { b: 'b' };171+172+ events.set('*', [star]);173+174+ inst.emit('foo', ea);175+ expect(star).to.have.been.calledOnce.and.calledWith('foo', ea);176+ star.resetHistory();177+178+ inst.emit('bar', eb);179+ expect(star).to.have.been.calledOnce.and.calledWith('bar', eb);180+ });181+ });182+});deleted:test/index.js-182 removed
1-import mitt from '..';2-import chai, { expect } from 'chai';3-import { spy } from 'sinon';4-import sinonChai from 'sinon-chai';5-chai.use(sinonChai);6-7-describe('mitt', () => {8- it('should default export be a function', () => {9- expect(mitt).to.be.a('function');10- });11-12- it('should accept an optional event handler map', () => {13- expect(() => mitt(new Map())).not.to.throw;14- const map = new Map();15- const a = spy();16- const b = spy();17- map.set('foo', [a, b]);18- const events = mitt(map);19- events.emit('foo');20- expect(a).to.have.been.calledOnce;21- expect(b).to.have.been.calledOnce;22- });23-});24-25-describe('mitt#', () => {26- let events, inst;27-28- beforeEach( () => {29- events = new Map();30- inst = mitt(events);31- });32-33- describe('on()', () => {34- it('should be a function', () => {35- expect(inst)36- .to.have.property('on')37- .that.is.a('function');38- });39-40- it('should register handler for new type', () => {41- const foo = () => {};42- inst.on('foo', foo);43-44- expect(events.get('foo')).to.deep.equal([foo]);45- });46-47- it('should register handlers for any type strings', () => {48- const foo = () => {};49- inst.on('constructor', foo);50-51- expect(events.get('constructor')).to.deep.equal([foo]);52- });53-54- it('should append handler for existing type', () => {55- const foo = () => {};56- const bar = () => {};57- inst.on('foo', foo);58- inst.on('foo', bar);59-60- expect(events.get('foo')).to.deep.equal([foo, bar]);61- });62-63- it('should NOT normalize case', () => {64- const foo = () => {};65- inst.on('FOO', foo);66- inst.on('Bar', foo);67- inst.on('baz:baT!', foo);68-69- expect(events.get('FOO')).to.deep.equal([foo]);70- expect(events.has('foo')).to.equal(false);71- expect(events.get('Bar')).to.deep.equal([foo]);72- expect(events.has('bar')).to.equal(false);73- expect(events.get('baz:baT!')).to.deep.equal([foo]);74- });75-76- it('can take symbols for event types', () => {77- const foo = () => {};78- const eventType = Symbol('eventType');79- inst.on(eventType, foo);80- expect(events.get(eventType)).to.deep.equal([foo]);81- });82-83- // Adding the same listener multiple times should register it multiple times.84- // See https://nodejs.org/api/events.html#events_emitter_on_eventname_listener85- it('should add duplicate listeners', () => {86- const foo = () => {};87- inst.on('foo', foo);88- inst.on('foo', foo);89- expect(events.get('foo')).to.deep.equal([foo, foo]);90- });91- });92-93- describe('off()', () => {94- it('should be a function', () => {95- expect(inst)96- .to.have.property('off')97- .that.is.a('function');98- });99-100- it('should remove handler for type', () => {101- const foo = () => {};102- inst.on('foo', foo);103- inst.off('foo', foo);104-105- expect(events.get('foo')).to.be.empty;106- });107-108- it('should NOT normalize case', () => {109- const foo = () => {};110- inst.on('FOO', foo);111- inst.on('Bar', foo);112- inst.on('baz:bat!', foo);113-114- inst.off('FOO', foo);115- inst.off('Bar', foo);116- inst.off('baz:baT!', foo);117-118- expect(events.get('FOO')).to.be.empty;119- expect(events.has('foo')).to.equal(false);120- expect(events.get('Bar')).to.be.empty;121- expect(events.has('bar')).to.equal(false);122- expect(events.get('baz:bat!')).to.have.lengthOf(1);123- });124-125- it('should remove only the first matching listener', () => {126- const foo = () => {};127- inst.on('foo', foo);128- inst.on('foo', foo);129- inst.off('foo', foo);130- expect(events.get('foo')).to.deep.equal([foo]);131- inst.off('foo', foo);132- expect(events.get('foo')).to.deep.equal([]);133- });134- });135-136- describe('emit()', () => {137- it('should be a function', () => {138- expect(inst)139- .to.have.property('emit')140- .that.is.a('function');141- });142-143- it('should invoke handler for type', () => {144- const event = { a: 'b' };145-146- inst.on('foo', (one, two) => {147- expect(one).to.deep.equal(event);148- expect(two).to.be.an('undefined');149- });150-151- inst.emit('foo', event);152- });153-154- it('should NOT ignore case', () => {155- const onFoo = spy(),156- onFOO = spy();157- events.set('Foo', [onFoo]);158- events.set('FOO', [onFOO]);159-160- inst.emit('Foo', 'Foo arg');161- inst.emit('FOO', 'FOO arg');162-163- expect(onFoo).to.have.been.calledOnce.and.calledWith('Foo arg');164- expect(onFOO).to.have.been.calledOnce.and.calledWith('FOO arg');165- });166-167- it('should invoke * handlers', () => {168- const star = spy(),169- ea = { a: 'a' },170- eb = { b: 'b' };171-172- events.set('*', [star]);173-174- inst.emit('foo', ea);175- expect(star).to.have.been.calledOnce.and.calledWith('foo', ea);176- star.resetHistory();177-178- inst.emit('bar', eb);179- expect(star).to.have.been.calledOnce.and.calledWith('bar', eb);180- });181- });182-});added:test/test-types-compilation.ts+43 added
12345678910111213141516171819202122232425262728293031323334353637383940414243/* eslint-disable @typescript-eslint/ban-ts-comment, @typescript-eslint/no-unused-vars */
import mitt from '..';
const emitter = mitt();
/* * Check that if on is provided a generic, it only accepts handlers of that type */{ const badHandler = (x: number) => {}; const goodHandler = (x: string) => {};
// @ts-expect-error emitter.on<string>('foo', badHandler); emitter.on<string>('foo', goodHandler);}
/* * Check that if off is provided a generic, it only accepts handlers of that type */{ const badHandler = (x: number) => {}; const goodHandler = (x: string) => {};
// @ts-expect-error emitter.off<string>('foo', badHandler); emitter.off<string>('foo', goodHandler);}
/* * Check that if emitt is provided a generic, it only accepts event data of that type */{ interface SomeEventData { name: string; } // @ts-expect-error emitter.emit<SomeEventData>('foo', 'NOT VALID'); emitter.emit<SomeEventData>('foo', { name: 'jack' });}
deleted:test/types.ts-20 removed
1234567891011121314151617181920import mitt, { EventHandlerList, EventHandlerMap } from '..';
const events = mitt();function foo() {}events.on('foo', foo);events.emit('foo', 'hello');
// handler return type should be ignored:events.on('foo', async e => e * 42);
// event map typeconst map = new Map<string, EventHandlerList>([ ['foo', [foo]]]);const events2 = mitt(map);events2.emit('foo', 'hello');
// event map type & iterablesconst map2 : EventHandlerMap = new Map(Object.entries(({ foo: [foo] })));mitt(map2);modified:.editorconfig+1 added
8 unmodified lines9 10 [{package.json,.*rc,*.yml}]11 indent_style = space12 indent_size = 213+insert_final_newline = false14 15 [*.md]16 trim_trailing_whitespace = false17 indent_style = space1 unmodified linemodified:.gitignore+1 added
1 /dist2 /test-reports3 /node_modules4 /npm-debug.log5+/index.d.ts6 package-lock.json7 .DS_Store8 .ideamodified:package.json+25 added-10 removed
6 unmodified lines7 "module": "dist/mitt.es.js",8 "esmodules": "dist/mitt.modern.js",9 "main": "dist/mitt.js",10 "umd:main": "dist/mitt.umd.js",11- "typings": "dist/index.d.ts",11+ "typings": "index.d.ts",12 "scripts": {13- "test": "npm-run-all --silent typecheck lint testonly",14- "testonly": "mocha --require esm test/**/*.js",13+ "test": "npm-run-all --silent typecheck lint mocha test-types",14+ "mocha": "mocha test",15+ "test-types": "tsc test/test-types-compilation.ts --noEmit",16 "lint": "eslint src test --ext ts --ext js",16- "typecheck": "tsc **/*.ts --noEmit",17+ "typecheck": "tsc --noEmit",18 "bundle": "microbundle",19 "build": "npm-run-all --silent clean -p bundle -s docs",20 "clean": "rimraf dist",21 "docs": "documentation readme src/index.ts --section API -q --parse-extension ts",12 unmodified lines34 ],35 "license": "MIT",36 "files": [37 "src",37- "dist"38+ "dist",39+ "index.d.ts"40 ],41+ "mocha": {42+ "extension": [43+ "ts"44+ ],45+ "require": [46+ "ts-node/register",47+ "esm"48+ ],49+ "spec": [50+ "test/*_test.ts"51+ ]52+ },53 "eslintConfig": {54 "extends": [55 "developit",56 "plugin:@typescript-eslint/eslint-recommended",24 unmodified lines81 "@typescript-eslint/no-empty-function": 082 }83 },84 "eslintIgnore": [71- "dist"85+ "dist",86+ "index.d.ts"87 ],88 "devDependencies": {89 "@types/chai": "^4.2.11",90 "@types/mocha": "^7.0.2",5 unmodified lines96 "documentation": "^13.0.0",97 "eslint": "^7.1.0",98 "eslint-config-developit": "^1.2.0",99 "esm": "^3.2.25",85- "microbundle": "^0.12.0",86- "mocha": "^7.2.0",100+ "microbundle": "^0.12.3",101+ "mocha": "^8.0.1",102 "npm-run-all": "^4.1.5",103 "rimraf": "^3.0.2",104 "sinon": "^9.0.2",105 "sinon-chai": "^3.5.0",91- "ts-node": "^8.10.1",106+ "ts-node": "^8.10.2",107 "typescript": "^3.9.3"108 }94-}109+}modified:README.md+1 added-1 removed
108 unmodified lines109 ### mitt110 111 Mitt: Tiny (~200b) functional event emitter / pubsub.112 113-Returns **Mitt**113+Returns **Mitt** 114 115 ### on116 117 Register an event handler for the given type.54 unmodified linesmodified:tsconfig.json+5 added-3 removed
12345667889910111213{ "compileOnSave": false, "compilerOptions": { "noEmit": true, "declaration": true, "moduleResolution": "node" "moduleResolution": "node", "esModuleInterop": true }, "exclude": [ "test" "include": [ "src/*.ts", "test/*.ts", ]}