Skip to content

Commit

Permalink
feat(store): warn when same action is registered (#1801)
Browse files Browse the repository at this point in the history
Closes #1758
  • Loading branch information
timdeschryver authored and brandonroberts committed Apr 25, 2019
1 parent 46678f2 commit ecda5f7
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
54 changes: 54 additions & 0 deletions modules/store/spec/reducer_creator.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as ngCore from '@angular/core';
import { on, createReducer, createAction, props, union } from '@ngrx/store';
import { expecter } from 'ts-snippet';

Expand Down Expand Up @@ -86,6 +87,59 @@ import {on} from './modules/store/src/reducer_creator';
state = fooBarReducer(state, bar({ bar: 54 }));
expect(state).toEqual(['[foobar] FOO', '[foobar] BAR']);
});

describe('warning message when the same action type gets registered', () => {
it('should not warn when not violated', () => {
const spy = spyOn(console, 'warn');

const fooBarReducer = createReducer(
[],
on(foo, state => state),
on(bar, state => state)
);

expect(spy).not.toHaveBeenCalled();
});

it('should warn in dev mode', () => {
const spy = spyOn(console, 'warn');

const fooBarReducer = createReducer(
[],
on(foo, state => state),
on(bar, state => state),
on(foo, state => state)
);

expect(spy).toHaveBeenCalledTimes(1);
});

it('should warn in dev mode with multiple actions', () => {
const spy = spyOn(console, 'warn');

const fooBarReducer = createReducer(
[],
on(foo, foo, state => state),
on(bar, state => state)
);

expect(spy).toHaveBeenCalledTimes(1);
});

it('should not warn in prod mode', () => {
spyOn(ngCore, 'isDevMode').and.returnValue(false);
const spy = spyOn(console, 'warn');

const fooBarReducer = createReducer(
[],
on(foo, state => state),
on(bar, state => state),
on(foo, state => state)
);

expect(spy).not.toHaveBeenCalled();
});
});
});
});
});
8 changes: 8 additions & 0 deletions modules/store/src/reducer_creator.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isDevMode } from '@angular/core';
import { ActionCreator, ActionReducer, ActionType, Action } from './models';

// Return type of the `on` fn.
Expand Down Expand Up @@ -51,8 +52,15 @@ export function createReducer<S>(
...ons: On<S>[]
): ActionReducer<S> {
const map = new Map<string, ActionReducer<S>>();
const devMode = isDevMode();

for (let on of ons) {
for (let type of on.types) {
if (devMode && map.has(type)) {
console.warn(
`@ngrx/store: The provided action type '${type}' is already provided.`
);
}
map.set(type, on.reducer);
}
}
Expand Down

0 comments on commit ecda5f7

Please sign in to comment.