ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests
MIT License
3.47k stars 245 forks source link

Return data is undefined #221

Closed javierguzman closed 5 years ago

javierguzman commented 5 years ago

Hello all,

I am using axios-mock-adapter with Storybook and I am having issues with the data returned. The strangest thing is that sometimes works but most of the times do not.

This is my code:

story.add("Successful log in", () => {
    axiosMock.onPost(url).reply(200, {
        type: successTypes.SUCCESS_LOGIN,
        payload: "UserID123"
    });
    console.log(axiosMock.handlers.post);
    return <Login />;
},{notes});

The console log always shows the handler has been added, so I am not sure why it does not work!

Any clue?

Thank you in advance and regards

gburning commented 5 years ago

I am not an expert on React but use Storybook for Vue. I have had to set up any requests I want to mock within the rendered component's lifecycle hooks, in this case created(). You could try doing something similar, I assume in componentDidMount()?

javierguzman commented 5 years ago

Thanks! But that would mean to modify the original source code rather than the story or the test, wouldn´t it? Also, that maybe works for component that makes the axios query when they are mounted, but that would not work for components that make the query when a button is clicked or something like that :(

gburning commented 5 years ago

But that would mean to modify the original source code rather than the story or the test, wouldn´t it?

No, it shouldn't. The function that you pass to .add() returns a component. Just make it return a wrapper component (with the lifecycle hook) that renders <Login />.

Also, that maybe works for component that makes the axios query when they are mounted, but that would not work for components that make the query when a button is clicked or something like that :(

Unless React does some strange cleanup between every lifecycle event it should not. This just makes sure that you're creating the mock adapter instance in the right scope.

javierguzman commented 5 years ago

@gburning Thanks! I understand now what you mean. I will try that in the following days.

javierguzman commented 5 years ago

I have discovered that if I place "const axiosMock = new MockAdapter(axios);" inside every story rather than doing that only once and reusing it for every story in that file, it works.

It is a pity I cannot reuse the object instance but I guess the garbage collector will take care of that...I do not fancy creating a new mock for every story but anyway... Also, I tried to call reset and resetHandler before but that did not work. Maybe it is related to the storybook webpack and how things get transpiled.. as I mentioned before, sometimes was working!

I will close this from now. I will write back if this happens again.