Last active
March 21, 2019 15:06
-
-
Save mharris717/37cb3001c1e81d3128077c0db09ed5c5 to your computer and use it in GitHub Desktop.
Instance Fetch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* global describe, it, beforeEach */ | |
import expect from "expect"; | |
import Identity from "../src/identity"; | |
import { create } from "../src/microstates"; | |
import { TodoMVC } from "./todomvc"; | |
import Promise from "bluebird"; | |
export default class FetchAttr { | |
constructor() { | |
this.loading = Boolean; | |
this.successCount = Number; | |
this.lastStatus = String; | |
this.errorMessage = String; | |
} | |
success() { | |
return this.loading | |
.set(false) | |
.successCount.increment() | |
.lastStatus.set("success") | |
.pendingAlertMessage.set("fetch succeeded"); | |
} | |
failure() { | |
return this.loading.set(false).lastStatus.set("failure"); | |
} | |
start() { | |
if (this.loading.state) { | |
throw `Tried to start but already loading`; | |
} | |
return this.loading.set(true); | |
} | |
reset() { | |
return this.loading.set(false); | |
} | |
get isFetching() { | |
return !!this.loading.state; | |
} | |
get isFetched() { | |
return !this.isLoading && this.lastStatus.state === "success"; | |
} | |
get runPromise() { | |
return fetchPromise => { | |
this.start(); | |
fetchPromise.then(() => this.success()).catch(() => this.failure()); | |
}; | |
} | |
} | |
class TodoFetch extends TodoMVC { | |
fetching = FetchAttr; | |
get fetchPromise() { | |
return Promise.delay(25).then(() => { | |
this.todos.set([{ name: "Stuff" }, { name: "More Stuff" }]); | |
}); | |
} | |
get fetch() { | |
return () => { | |
return this.fetching.runPromise(this.fetchPromise); | |
}; | |
} | |
get numTodos() { | |
return this.todos.length; | |
} | |
} | |
describe("fetch", () => { | |
let initial; | |
let latest; | |
let store; | |
beforeEach(() => { | |
latest = null; | |
initial = create(TodoFetch, { | |
todos: [{ name: "Things" }] | |
}); | |
store = Identity(initial, newState => { | |
latest = newState; | |
}); | |
expect(initial.numTodos).toEqual(1); | |
expect(store.numTodos).toEqual(1); | |
}); | |
it("success", () => { | |
store.fetch(); | |
expect(latest.numTodos).toEqual(1); | |
expect(latest.fetching.isFetching).toEqual(true); | |
Promise.delay(10).then(() => { | |
expect(latest.fetching.isFetching).toEqual(true); | |
}); | |
Promise.delay(30).then(() => { | |
expect(latest.fetching.isFetching).toEqual(false); | |
expect(latest.fetching.isFetched).toEqual(true); | |
}); | |
return Promise.delay(50).then(() => { | |
expect(latest.numTodos).toEqual(2); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment