Skip to content

Instantly share code, notes, and snippets.

@dmueller39
Created September 14, 2016 15:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmueller39/8764afc2c2c26ca2f164d416aabcafc9 to your computer and use it in GitHub Desktop.
Save dmueller39/8764afc2c2c26ca2f164d416aabcafc9 to your computer and use it in GitHub Desktop.
Testing Async redux actions in jest
function update(value) {
return (dispatch) => new Promise((resolve) => setImmediate(
() => {
dispatch({ type: 'UPDATE', value });
resolve();
}
));
}
describe('async action', () => {
pit('dispatches an update action passing the action to resolve',
// returning a new Promise guarantees that
// pit will wait until the 'then' block has been called
() => new Promise((resolve) => {
// pass in resolve as our dispatch
update(1)(resolve);
}).then(
// by calling resolve as the dispatch we now can test the action
(action) => {
expect(action).not.toBeNull();
expect(action.type).toBe('UPDATE');
expect(action.value).toBe(1);
}
)
);
pit('dispatches an update action storing the results in a scoped variable', () => {
// collect the results in a variable with a shared scope between
// the 'promise' block and the 'then' block
let receivedAction = null;
// returning a new Promise guarantees that
// pit will wait until the 'then' block has been called
return new Promise((resolve) => {
const dispatch = (action) => {
receivedAction = action;
resolve();
};
update(1)(dispatch);
}).then(
// this block is only called if dispatch calls 'resolve' above
() => {
expect(receivedAction).not.toBeNull();
expect(receivedAction.type).toBe('UPDATE');
expect(receivedAction.value).toBe(1);
}
);
});
});
@palexs
Copy link

palexs commented Sep 20, 2016

Hi, Daniel,

I've been reading about async testing in jest and found one thing. It's possible to use parameter to the pit function and it will make a test wait until this parameter is called explicitly. For example,


// *** Using promises ***
pit('gets data from AsyncStorage', function () {
    return new Promise((resolve) => {
      OfflineTrackingStorage.get()
        .then(
          (result) => {
            expect(receivedKey).toBe(KEY_TRACKING_DATA);
            expect(result[0].test_get_field).toBe('somevalue');
            resolve();
          });
    });
  });
// *** Using function parameter done ***
pit('gets data from AsyncStorage', function (done) {
      OfflineTrackingStorage.get()
        .then(
          (result) => {
            expect(receivedKey).toBe(KEY_TRACKING_DATA);
            expect(result[0].test_get_field).toBe('somevalue');
            done();
          });
  });

IMHO, version with promises is less readable. What do you think?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment