Skip to content

Instantly share code, notes, and snippets.

@ajcrites
Created June 21, 2017 04:21
Show Gist options
  • Save ajcrites/b8d73ac7076512111004cedf7599a7fb to your computer and use it in GitHub Desktop.
Save ajcrites/b8d73ac7076512111004cedf7599a7fb to your computer and use it in GitHub Desktop.
// Make an API asynchronous
// In this example, we mock an iOS Keychain class. All operations
// are async (I/O), so when we use this mock in our tests, we
// want the operations to act async even though it's not needed
// for the class to work
class KeychainMock {
store: [],
async get(key) {
return this.store[key] || null;
}
async set(key, value, useTouchId) {
this.store[key] = { value, useTouchId };
}
async remove(key) {
delete this.store[key];
}
}
/* Promises implementation */
// `async` wraps functions in promises very neatly.
class KeychainMock {
store: [],
get(key) {
return Promise.resolve(this.store[key] || null);
}
set(key, value, useTouchId) {
this.store[key] = { value, useTouchId };
return Promise.resolve();
}
async remove(key) {
delete this.store[key];
return Promise.resolve();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment