2

I am using a Redis cache in a few API files, meaning I have a dependency that I need to mock in tests. Let's say I have the following file structure

-api 
   - login.js *
   - login.spec.js
   - initiate.js 
   - initiate.spec.js
   - user.js *
   - user.spec.js
- routes.js
- server.js

Let's say those files with the * have redis-connection as a dependency, which I can then mock in the respective spec.js using Proxyquire.

Easy.

Problem comes when I then run all my tests, and Mocha boots up the server. All of these files will be brought in my routes.js and it fails because Redis is not running. I can see a few ways round this:

  1. Globally mock proxyquire - The docs don't like this.
  2. My current workaround, in each file where redis-connection is required, conditionally import either the real thing or a basic mock if process.env.NODE_ENV === 'test'. Then proxyquire this mock to a more useful mock in the relevant spec file if you need specific behaviour. Convoluted, but seems to work.
  3. Create a mock for each occurance of redis-connection in every spec file. Sounds horrible to manage. Might also not work when Mocha initially runs the server

Are there any other ways round this? I feel like my workaround might work for the time being as I'm not using this dependency very often, but I would prefer a more scalable solution.

Thanks

MDalt
  • 1,681
  • 2
  • 24
  • 46

0 Answers0