ctimmerm / axios-mock-adapter

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

axios mocking with monorepos #198

Open kldavis4 opened 5 years ago

kldavis4 commented 5 years ago

I have a monorepo containing a react frontend, a node backend using babel for es6 import syntax support and a common library. The common library (also using babel) has some api client code built on axios. Recently I've been migrating this monorepo from yarn workspaces + lerna to npm + lerna. After making the change I discovered that unless I use lerna bootstrap --hoist, I am unable to mock axios in the common library for tests in the backend. It seems to be getting a different axios instance than the one that I import. I realize that this isn't necessarily a problem with axios-mock-adapter, but I am wondering if anyone else has run into similar issues and has suggestions other than to use hoist.

ochikov commented 5 years ago

@kldavis4 I have similar issues. My tests are in a main folder and not in the every package of the monorepo packages. Again mocking failed because someway it does not catch the axios instance. In the main package.json in the monorepo, I placed in "dependencies", the axios dependency and it works.

ochikov commented 5 years ago

Another possible solution is to load theaxios from your packages/desired-package/node-modules. For example: var axios = require('../../../packages/YOUR_PACKAGE_NAME/node_modules/axios');

And then give it to the MockAdapter

rally25rs commented 5 years ago

Another possible solution to this kind of problem is to make a vendors or thirdParty module that imports and re-exports 3rd party libraries. Then all your packages use that one. Something like:

vendors.js

export {default as axios} from 'axios';

packages/libraryOne/whatever.js

import {axios} from 'vendors';

packages/libraryTwo/whatever.js

import {axios} from 'vendors';

they should all end up with the same single instance exported by the vendors module.