Giter Site home page Giter Site logo

jihchi / res-msw Goto Github PK

View Code? Open in Web Editor NEW
11.0 3.0 2.0 1.09 MB

Mock Service Worker (MSW) bindings for ReScript

License: MIT License

JavaScript 45.45% HTML 0.99% ReScript 53.56%
msw mock mocking mocking-framework service-worker mocking-library reasonml bucklescript bucklescript-bindings bindings

res-msw's Introduction

res-msw

Travis (.org) npm Coveralls github npm NPM

msw bindings for ReScript (formerly known as BuckleScript in Reason)

Installation

Prerequisite: you have installed msw.

npm install -D res-msw

Or if you are using yarn:

yarn add -D res-msw

Usage

Add res-msw to your bsconfig.json:

  ...
  "bs-dependencies": [
+   "res-msw"
  ]
  ...

API

ResMsW.MSW is the root namespace, includes following namespaces and modules:

  • rest
  • graphql
  • Node module
  • ServiceWorker module
  • Rest module
  • GraphQL module

Node module

  • setup(array(requestHandler))
  • server |> listen()
  • server |> close()
  • server |> resetHandlers()
  • server |> restoreHandlers()
  • server |> user(requestHandler)
  • rest |> get(string, (req, res, ctx) => { });
  • rest |> post(string, (req, res, ctx) => { });
  • rest |> put(string, (req, res, ctx) => { });
  • rest |> patch(string, (req, res, ctx) => { });
  • rest |> delete(string, (req, res, ctx) => { });
  • rest |> options(string, (req, res, ctx) => { });

ServiceWorker module

  • setup(array(requestHandler))
  • worker |> start()
  • worker |> stop()
  • worker |> resetHandlers()
  • worker |> restoreHandlers()
  • worker |> user(requestHandler)
  • graphql |> query(string, (req, res, ctx) => { });
  • graphql |> mutation(string, (req, res, ctx) => { });

Rest module

  • res |> mock(array(responseTransformer))
  • res |> mockOnce(array(responseTransformer))
  • ctx |> status(int)
  • ctx |> set(string, string)
  • ctx |> delay(int)
  • ctx |> fetch(req)
  • ctx |> text(string)
  • ctx |> json(Js.Json.t)
  • ctx |> xml(string)

GraphQL module

  • res |> mock(array(responseTransformer))
  • res |> mockOnce(array(responseTransformer))
  • ctx |> status(int)
  • ctx |> set(string, string)
  • ctx |> delay(int)
  • ctx |> fetch(req)
  • ctx |> data(Js.Json.t)
  • ctx |> errors(array(Js.Json.t))

Example of Rest

For more example, please refer to MSW_node_test.re and mocks.re.

open ResMsw.MSW

let getRepoInfo = rest |> get("https://api.github.com/repos/:owner/:repo", (
  req,
  res,
  ctx,
) => {
  let {params} = req
  let owner = params->Js.Dict.get("owner")->Belt.Option.getWithDefault("N/A")
  let repo = params->Js.Dict.get("repo")->Belt.Option.getWithDefault("N/A")

  res |> Rest.mock([
    ctx |> Rest.status(200),
    ctx |> Rest.text(`owner: ${owner}, repo: ${repo}`),
  ])
})

let getRepoInfoError =
  rest |> get("https://api.github.com/repos/:owner/:repo", (req, res, ctx) =>
    res |> Rest.mock([ctx |> Rest.status(500), ctx |> Rest.text("Oops")])
  )

let server = Node.setup([getRepoInfo])

server->listen()
server->use(getRepoInfoError)
server->restoreHandlers()
server->resetHandlers()
server->close()

Example of GraphQL

For more example, please refer to MSW_browser.re and mocks.re.

open ResMsw.MSW

let queryUserDetail = graphql |> query("GetUserDetail", (req, res, ctx) => {
  let name = ("name", req.variables["name"])
  let data = Js.Dict.fromList(list{name}) |> Js.Json.object_

  res |> GraphQL.mock([ctx |> GraphQL.status(200), ctx |> GraphQL.data(data)])
})

let queryUserDetailError = graphql |> query("GetUserDetail", (
  req,
  res,
  ctx,
) => {
  let message = (
    "message",
    Js.Json.string(`This is a mocked error: ${req.variables["name"]}`),
  )
  let location = Js.Dict.fromList(list{
    ("line", Js.Json.number(1.0)),
    ("column", Js.Json.number(2.0)),
  })
  let locations = ("locations", Js.Json.objectArray([location]))
  let error = Js.Dict.fromList(list{message, locations}) |> Js.Json.object_

  res |> GraphQL.mock([
    ctx |> GraphQL.status(200),
    ctx |> GraphQL.errors([error]),
  ])
})

let worker = ServiceWorker.setup([queryUserDetail])

worker->start()
worker->use(GetUserDetailError)
worker->restoreHandlers()
worker->resetHandlers()
worker->stop()

Testing the library

npm test

this will compile and execute tests with bs-jest

Contributions

Don't hesitate to open a PR with a new binding - while bumping up the amount of covered bindings in the README. There are tests, use them and write the most simple test you can think of to make sure that the bindings work correctly.

res-msw's People

Contributors

dependabot[bot] avatar jihchi avatar srikanthkyatham avatar vloth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

res-msw's Issues

Expose request body for rest (feature request)

It's fairly common to access the message body whenever the rest method is POST or PUT. I did a quick test changing the type of request to {params: Js.Dict.t<string>, body: Js.Dict.t<string>}, but not sure if that's the best way.
Are there any plans to support this in the near future?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.