Skip to content

Commit

Permalink
Add simple test for setSelf() in onSet()
Browse files Browse the repository at this point in the history
Summary: Add a simple test for the use-case of always transforming an atom value with an effect using `setSelf()` in `onSet()` based on concern in facebookexperimental#1582.

Reviewed By: habond

Differential Revision: D33908670

fbshipit-source-id: f9da1c1c19fb45c1c439bc0427d9e95d6ae031b3
  • Loading branch information
drarmstr authored and facebook-github-bot committed Feb 3, 2022
1 parent 304b468 commit e14a9f7
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions packages/recoil/recoil_values/__tests__/Recoil_atom-test.js
Expand Up @@ -555,6 +555,81 @@ describe('Effects', () => {
},
);

testRecoil('Always call setSelf() in onSet() handler', () => {
const myAtom = atom({
key: 'atom setSelf in onSet',
default: 'DEFAULT',
effects: [
({setSelf, onSet}) => {
onSet(newValue => {
setSelf('TRANSFORM ' + newValue);
});
},
],
});

const [ReadsWritesAtom, setAtom] = componentThatReadsAndWritesAtom(myAtom);

const c = renderElements(<ReadsWritesAtom />);
expect(c.textContent).toEqual('"DEFAULT"');

act(() => setAtom('SET'));
expect(c.textContent).toEqual('"TRANSFORM SET"');

act(() => setAtom('SET2'));
expect(c.textContent).toEqual('"TRANSFORM SET2"');
});

testRecoil('Patch value using setSelf() in onSet() handler', () => {
let patch = 'PATCH';
const myAtom = atom({
key: 'atom patch setSelf in onSet',
default: {value: 'DEFAULT', patch},
effects: [
({setSelf, onSet}) => {
onSet(newValue => {
if (
!(newValue instanceof DefaultValue) &&
newValue.patch != patch
) {
setSelf({value: 'TRANSFORM_ALT ' + newValue.value, patch});
}
});
},
({setSelf, onSet}) => {
onSet(newValue => {
if (
!(newValue instanceof DefaultValue) &&
newValue.patch != patch
) {
setSelf({value: 'TRANSFORM ' + newValue.value, patch});
}
});
},
],
});

const [ReadsWritesAtom, setAtom] = componentThatReadsAndWritesAtom(myAtom);

const c = renderElements(<ReadsWritesAtom />);
expect(c.textContent).toEqual('{"patch":"PATCH","value":"DEFAULT"}');

act(() => setAtom(x => ({...x, value: 'SET'})));
expect(c.textContent).toEqual('{"patch":"PATCH","value":"SET"}');

act(() => setAtom(x => ({...x, value: 'SET2'})));
expect(c.textContent).toEqual('{"patch":"PATCH","value":"SET2"}');

patch = 'PATCHB';
act(() => setAtom(x => ({...x, value: 'SET3'})));
expect(c.textContent).toEqual(
'{"patch":"PATCHB","value":"TRANSFORM SET3"}',
);

act(() => setAtom(x => ({...x, value: 'SET4'})));
expect(c.textContent).toEqual('{"patch":"PATCHB","value":"SET4"}');
});

// NOTE: This test throws an expected error
testRecoil('reject promise', async () => {
let rejectAtom;
Expand Down

0 comments on commit e14a9f7

Please sign in to comment.