martyjs / marty

A Javascript library for state management in React applications
http://martyjs.org
MIT License
1.09k stars 76 forks source link

testing stores #188

Closed vid closed 9 years ago

vid commented 9 years ago

I want to test interaction with my stores (not the rest of components) at an integration level. I can't figure out how to mock or get around the HTTP state source's dependency on browser fetch. Is there any way to mock just this part of a test? Can Marty recognize it's not running in a browser and use an alternate fetch mechanism?

I see a discussion at https://github.com/jhollingworth/marty/issues/115 but there's no complete answer. I have tried mocking an HttpAPI instance without success and it's taking me off the supported path. Knowing 0.9 supports server rendering I'm wondering if there's a way to do this today.

Thanks!

jhollingworth commented 9 years ago

Hey, there are a couple of strategies you could try

1) Stub StateSource#request (or StateSource#get/post/put/delete)

sinon.stub(SomeStateSource, "request").returns(Promise.resolve({
  body: {
    foo: { bar: "baz" }
  }
})

2) Uses sinon's fakeServer

docs

var expectedState = { bar: "baz" };
var server = sinon.fakeServer.create();

server.respondWith(
  "GET",
  "/foo",
  [200, { "Content-Type": "application/json" }, JSON.stringify(expectedState)]
);

FooStore.getFoo();

server.respond();

expect(FooStore.getFoo().result).to.eql(expectedState);

While a bit more complicated I prefer using fakeServer as it tests more.

vid commented 9 years ago

thanks, I've been trying to work with those but still in the fog.

I've also been messing around with using sequence diagrams generated from http://bramp.github.io/js-sequence-diagrams/ but it struck me this would be really effective at the live, instrumented level. Have you considered that?

jhollingworth commented 9 years ago

Thats a cool idea. I'd like to do something like that in the devtools but its just finding the time....