Skip to content

Instantly share code, notes, and snippets.

@timdeschryver
Created September 3, 2019 18:39
Show Gist options
  • Select an option

  • Save timdeschryver/43a3337e09a0e1e857d11c317d13439c to your computer and use it in GitHub Desktop.

Select an option

Save timdeschryver/43a3337e09a0e1e857d11c317d13439c to your computer and use it in GitHub Desktop.
describe('createSelectorFactoryWithCache', () => {
const mockState = {
propA: {
a: 1,
b: 2,
c: 3,
},
propB: {
d: 4,
e: 5,
f: 6,
},
};
const selectPropA = createFeatureSelector<typeof mockState.propA>('propA');
describe('Use a selector created by createSelectorFactoryWithCache', () => {
let selectCMultipliedBy: any;
let insideProjection: jasmine.Spy;
beforeEach(() => {
insideProjection = jasmine.createSpy('projection');
selectCMultipliedBy = createSelector(
selectPropA,
(propA: { a: number; b: number; c: number }, multiplier: number) => {
insideProjection();
return propA.c * multiplier;
}
);
});
it('Should select the correct data', () => {
expect(selectCMultipliedBy(mockState, 4)).toEqual(
mockState.propA.c * 4
);
});
describe('Using the selector with several different parameters', () => {
it('projection function should be called once for each parameter', () => {
const times5 = selectCMultipliedBy(mockState, 5);
const times7 = selectCMultipliedBy(mockState, 7);
expect(insideProjection).toHaveBeenCalledTimes(2);
});
// ! this one will fail, will be called 3 times !
it('projection function should not be called again if called with the same parameter', () => {
const times5 = selectCMultipliedBy(mockState, 5);
const times7 = selectCMultipliedBy(mockState, 7);
const times5again = selectCMultipliedBy(mockState, 5);
expect(insideProjection).toHaveBeenCalledTimes(2);
});
it('selector data should be correct even when called with different params', () => {
const times5 = selectCMultipliedBy(mockState, 5);
const times7 = selectCMultipliedBy(mockState, 7);
const times5again = selectCMultipliedBy(mockState, 5);
const times7again = selectCMultipliedBy(mockState, 7);
expect(times5).toEqual(mockState.propA.c * 5);
expect(times5again).toEqual(mockState.propA.c * 5);
expect(times7).toEqual(mockState.propA.c * 7);
expect(times7again).toEqual(mockState.propA.c * 7);
});
});
describe('underlying state change', () => {
it('projection should be called again if state changed', () => {
expect(selectCMultipliedBy(mockState, 5)).toEqual(
mockState.propA.c * 5
);
expect(insideProjection).toHaveBeenCalledTimes(1);
expect(selectCMultipliedBy(mockState, 5)).toEqual(
mockState.propA.c * 5
);
expect(insideProjection).toHaveBeenCalledTimes(1);
expect(
selectCMultipliedBy(
Object.assign({}, mockState, { propA: { c: 100 } }),
5
)
).toEqual(500);
expect(insideProjection).toHaveBeenCalledTimes(2);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment