mswjs / msw-storybook-addon

Mock API requests in Storybook with Mock Service Worker.
https://msw-sb.vercel.app
MIT License
408 stars 39 forks source link

Angular Support #16

Closed sonicparke closed 3 years ago

sonicparke commented 3 years ago

Is there any reason this wouldn't work with Angular? It seems like it's not actually intercepting my requests.

It looks like it should've worked but it's returned the data from the actual endpoint and not what I've mocked: image

According to the console MSW is enabled image

Here is my story where I'm adding the params:

export const primary = () => ({
  moduleMetadata: {
    imports: [HttpClientModule],
  },
  component: MyComponent,
  parameters: {
    msw: [
      rest.get('/api/unauthed', (req, res, ctx) => {
        return res(
          ctx.json({
            config: 'myConfig'
          })
        );
      }),
    ],
  },
});

preview.js

import { addDecorator, addParameters } from '@storybook/angular';
import { withKnobs } from '@storybook/addon-knobs';
import { withA11y } from '@storybook/addon-a11y';
import { create } from '@storybook/theming';
import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';
import { initializeWorker, mswDecorator } from 'msw-storybook-addon';

initializeWorker();
addDecorator(mswDecorator);
addDecorator(withKnobs);
addDecorator(withA11y);

const theme = create({
  base: 'light',
  brandTitle: 'MyOrg',
  fontBase: '"Open Sans", sans-serif',
  brandImage: 'assets/logo.svg',
});

addParameters({
  options: {
    theme,
    showRoots: true,
  },
  viewport: {
    viewports: INITIAL_VIEWPORTS,
  },
});

angular.json

    "storybook": {
      "projectType": "application",
      "root": "apps/storybook",
      "sourceRoot": "apps/storybook/src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
              ...
              "assets": [
                "apps/storybook/src/mockServiceWorker.js"
             ]
           }
         }
       }
    }

Am I missing something?

itaditya commented 3 years ago

Hey @sonicparke I don't work with Angular so I read some blogs and the official MSW example to get some info. From that, it looks like you're doing everything right.

Can you tell me what's the purpose of this snippet in the story file?

  moduleMetadata: {
    imports: [HttpClientModule],
  },

Another thing you can try is to clone the below repo and try to use the same handler, config in your example. https://github.com/mswjs/examples/tree/master/examples/rest-angular

It would let me know if something is wrong with my addon or is it a different problem.

Also if you could create a reproduction repo with your storybook config that would be really great.

itaditya commented 3 years ago

Closed due to inactivity. Feel free to re-open it.