stampit-org / stampit

OOP is better with stamps: Composable object factories.
https://stampit.js.org
MIT License
3.02k stars 102 forks source link

Can't seem to mock axios in a stamp #357

Closed raynmakers closed 1 year ago

raynmakers commented 1 year ago

Hi there,

I'm trying to write a unit test that tests my stamp, this is the setup of my files:

useFetch.ts

import stampit from '@stamp/it';
import axios from 'axios';

export default stampit({
  init({
    baseURL,
    headers
  }: {
    baseURL: string;
    headers: object;
  }) {
    this.fetch = axios.create({
      baseURL: this.baseURL || baseURL,
      headers: this.headers || headers
    });
  },
  methods: {
    async setQuery(params: string) {
      if (!this.query) {
        this.query = `?${params}`;
      } else {
        this.query = `${this.query}&${params}`;
      }
    },
    async request(url: string, type: string) {
      try {
        const fullURL: string = `${url || '/'}${this.query || ''}`
        return await this.fetch.get(fullURL);
      } catch (error) {
        throw error;
      }
    }
  }
});

And my test file:

import MockAdapter from 'axios-mock-adapter';
import { expect, assert } from 'chai'; 
import sinon from 'sinon';
import useFetch from './useFetch';
import axios, { AxiosError } from 'axios';
import stampit from '@stamp/it';

describe("useFetch", function() {
  describe("get", async () => {

    let stub: MockAdapter;
    const receivedData = { data: 'data' };

    before(() => {
      stub = new MockAdapter(useFetch());
      stub.onGet('https://google.com').replyOnce(200, receivedData);
    });

    it("returns data in a string", async () => {
      const response = await useFetch({
        baseURL: 'https://google.com'
      }).request();

      expect(response.status).to.be.equal(200);
      expect(response.data).to.be.deep.equal(receivedData);
    });

    after(() => {
      stub.restore();
    });
  });
});

What should I do to make this test work?

koresar commented 1 year ago

Thanks for your question.

Everything seems right. What's not working though?

raynmakers commented 1 year ago

It is calling the original Axios instance instead of the MockedAdapter.

koresar commented 1 year ago

Ah, mate, you need to ask the question in the axios and axios-mock-adapter projects respectively. I do not see you are using Stamps for mocking.

With stamps, one do not need any mocking libraries. Stampit can mock anything. Here is an article on that topic: https://medium.com/@koresar/fun-with-stamps-episode-17-easy-100-unit-test-coverage-in-js-d97e09591f18