Mocking odata endpoints in mswjs

150 Views Asked by At

Is it possible to mock odata endpoints using mswjs?

I currently use json-server as my temporary backend until the odata endpoint is ready, at which point I’ll migrate my queries to use that. I plan to use mswjs to mock the server in my tests, but would like to migrate now to use for development too.

Is it possible to replicate the odata filter functionality, or will I need to define explicit endpoints for each possible $filter query I want to use for testing?

Eg ‘/users$filter=id in (‘1’, ‘2’)’

I’m unsure how to replicate the $filter functionality that I need.

1

There are 1 best solutions below

0
kettanaito On

You can use MSW to intercept OData requests and mock their responses. Since the structure of OData pathnames is unique, I recommend creating a permissive request handler for the entire endpoint and then using some official or third-party tooling to parse that pathname to support things like $filter.

Here's an example of such a setup:

// handlers.js
import { rest } from 'msw'

export const handlers = [
  // Use a wildcard in the request URL predicate to
  // intercept all the matching requests to this endpoint:
  // - GET /api/users$filter=XYZ
  // - GET /api/articles$prop=ABC
  rest.get('/api/*', (req, res, ctx) => {
    const { pathname } = req.url 
    // Use some package to do the parsing correctly.
    const parsed = parseODataPathname(pathname)

    // I'm assuming the parsed structure here,
    // this is a pseudo-code. Adjust to that actual
    // returned data structure of the parser you find.
    if (parsed.filter) {
      return res(ctx.json({ some: 'data' }))
    }
  })
]

Just by searching the web for a minute, I found odata-filter-parser and odata/parser. You can find something even better suited for your use case.