mswjs/data - toHandlers function results in result 500

45 views Asked by At

I want to use mswjs/data and especially the toHandlers-function to simply create an API for testing purposes.

service.ts

const db = factory({
  user: {
    id: primaryKey(String),
    firstName: String,
  },
})

// Generates REST API request handlers.
const handlers = db.user.toHandlers('rest')

export const worker = setupWorker(...handlers)

toHandlers is supposed to create CRUD-methods for the user-object.

I created a simple React-project using axios for consuming the API:

index.tsx

import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { seedDb } from './service';


async function enableMocking() {
  if (process.env.NODE_ENV !== 'development') {
    return
  }
 
  const { worker } = await import('./service')

  return worker.start()
}

enableMocking().then(() => {
  const root = ReactDOM.createRoot(
    document.getElementById('root') as HTMLElement
  );
  root.render(
      <App />
  );
})

App.tsx

import axios from 'axios';
import { useEffect, useState } from 'react';

function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    axios.get('/users').then(v => {
        setUsers(JSON.parse(v.data));
    })
  }, [] )
  
  return (
    <div>
      { users.map(v => 
        <p key={v['id']}>
          {v['firstName']}
        </p>
      ) }
    </div>
  );
}

export default App;

The Code is pretty much following the documentation of mswjs/data, but unfortunately the calls always result in a 500. Can anyone tell me where the problem is?

I published this little test-project on github: https://github.com/DerRick79/mswjs-data-test

I manually created a users-method to get all users like this instead of the toHandlers-function:

const handlers = [
  http.get('/users', ({}) => {
    const data = JSON.stringify(db.user.getAll());
    return HttpResponse.json(data);
  })
]

This worked fine, so I don't see a problem with axios here.

1

There are 1 answers

0
Sems Samaras On

Try this one:

const handlers = db.user.toHandlers('rest', '/api/')