axios / moxios

Mock axios requests for testing

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't seem to use the baseURL defined in Axios default configuration

rfgamaral opened this issue · comments

For context, I'm using TypeScript, React and Jest with Enzyme.

On my application I'm doing something like this:

import * as React from "react";

import Axios from "axios";

export default class Application extends React.Component<any, any> {

    public constructor() {
        super();

        Axios.defaults.baseURL = "https://hostname.herokuapp.com";
    }

    public componentWillMount(): void {
        Axios.get("/token")
            .then((response) => {
                console.log(response);
            });
    }

}

And I'm trying to stub the /token request like this:

import * as React from "react";
import * as Moxios from "moxios";

import { shallow } from "enzyme";

import Application from "components/Application";

describe("Application", () => {

    Moxios.install();

    test("something", () => {
        shallow(<Application />);

        Moxios.stubRequest("/token", {
            status: 200,
            response: {
                message: "Hello Axios"
            }
        });
    });

});

The console.log(response); should output my mocked response, but it's not. However, if I change the stubRequest call to:

Moxios.stubRequest("https://hostname.herokuapp.com/token", ...);

It works... But that kinda defeats the purpose of the baseURL property. Well, it works on the code so that's not too bad, but why is it not working on testing too?

I've tried I've also tried this:

Moxios.install(Axios.create({
    baseURL: "https://hostname.herokuapp.com"
}));

But it didn't work...

What am I missing?

I make the test works, but without moxios instead with sinon like this.

it('should get posts on componentWillMount', () => {
  let posts = {data: [{id: 1}, {id: 2}, {id: 3}]};
  const promise = Promise.resolve(posts);
  sinon.stub(axios, 'post', () => promise);
  let wrapper = mount(<Posts />);
  return promise.then(() => {
    expect(wrapper.state().posts).toEqual(posts.data);
  });
})

I hope this help you @rfgamaral

I hope #25 fixes this too

@developersoul I've been trying to do the same with Jest spies and mock functionality (after reading your post) and have successfully tested everything without Moxios. Thank you.