4 ms·
Pardon my pseudo-JavaScript, but given an event handler like this: const handler = ( message, data, req=superagent.post ) =
by bigmanwalter 6y ago
Pardon my pseudo-JavaScript, but given an event handler like this:
const handler = (
message,
data,
req=superagent.post
) => {
if (message === “a”)
return req(“/api/a”, data)
if (message === “b”)
return {label:”b”, value: req(“/api/b”)}
}
By supplying the http client using the default argument on line 4, the client can be replaced when testing with a mock handler:
test(“handler requests /api/a”, t=>
t.assertDeepEqual(
handler(“a”, {b:”c”}, (url, body)=>[url, body])
[“/api/a”, {b:”c”}]
)
)
test(“handler requests /api/b”, t=>
t.assertDeepEqual(
handler(“b”, {b:”c”}, (url, body)=>[url, body])
{label:”b”, value:[“/api/b”, {b:”c”}]}
)
)
You could also write test cases that handle multiple steps, complex transformations, and so on.
It’s really nice being able to specify plainly the inputs and expected outputs of your functions and testing against that! It may not guarantee that everything behaves as the real system but it will catch 100% of your logic errors.