5

I'm trying to mock API calls from Detox tests and nothing seems to be working. Nock in theory would do exactly what I want but there when I run my tests with nock debugging it isn't seeing any of the requests being made from my app. I'm using axios to make requests and I've tried setting the adapter on my axios instance to the http adapter.

Any suggestions on how to get nock working with Detox or if there is another mocking library you have had success with is appreciated, thanks!

1 Answers1

3

What I ended up doing was leveraging the mocking specified in Detox docs (a separate *.e2e.js file hitting a different endpoint during tests). You define these special files that only run during e2e, I've set mine up to only hit localhost:9091 -- I then run an Express server on that port serving the endpoints I need.

Maybe an ugly way to do it, would love suggestions!

My mock file:

// src/helpers/axios.e2e.js
import axios from 'axios';

const instance = axios.create({
    baseURL: `http://localhost:9091/api`,
});

export default instance;

Here's how I am running an express server during tests:

// e2e/mytest.e2e.js
const express = require('express');
let server;

beforeAll(async () => {
    const app = express();

    app.post('/api/users/register/', (req, res) => {
      res.status(400)
      res.send({"email": ["Test error: Email is required!"]})
    })

    await new Promise(function(resolve) {
        server = app.listen(9091, "127.0.0.1", function() {
            console.log(` Running server on '${JSON.stringify(server.address())}'...`);
            resolve();
        });
    });
})

afterAll(() => {
    server.close()
})
Eric Carmichael
  • 560
  • 4
  • 15