0

I'm asking this after a lot of research

I have these files

// connection.js
const mysql =  require('mysql');
module.exports = mysql.getConnection();
// a.js
const connection = require('./connection');
function doQuery() {
    const q = 'select * from table';
    connection.query(q, (err, res) => {
       ... do some stuff
    })
}
module.exports = doQuery;

When I what to do a test with jest (deleting unnecessary things to better read)

// test.js
const jest = require('jest');
const a = require('./a.js');
const connection = {
  query: (query, cb) => cb('error', null),
};
jest.mock('./connection.js', () => connection);


test('testing something', () => {
    expect(a.doQuery).to.be.true //this is just an example
});

I'm getting the next error

The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
    Invalid variable access: connection

I tried moving the files in the same folder, with relative paths, absolute paths, moving the order of imports, and I really can't get it.

I really don't know how to fix this, also I'm migrating from proxyquire to jest that is the reason that I'm doing this and I can't use proxyquire anymore.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Julian Mendez
  • 3,162
  • 2
  • 13
  • 36
  • Does this answer your question? [Service mocked with Jest causes "The module factory of jest.mock() is not allowed to reference any out-of-scope variables" error](https://stackoverflow.com/questions/44649699/service-mocked-with-jest-causes-the-module-factory-of-jest-mock-is-not-allowe) – skyboyer Apr 15 '20 at 21:18
  • Didn't work. damn it – Julian Mendez Apr 16 '20 at 16:37
  • well, I used external variable twice or 3 times with using `mock*` names for them. if you will ever be really needed that, try different version of Jest, may be a bug. – skyboyer Apr 16 '20 at 17:38
  • That was one of the things that might work, but I already found how to solve it. Answer is already posted. Thant you! – Julian Mendez Apr 16 '20 at 18:22

1 Answers1

0

Yeah, well... Gonna answer my very own question for the future.

The thing is that you cant use variables that are declared outside the jest.mock() function as I am doing.

The test file and the mock function should be something like this

Solution 1

jest.mock('./connection.js', () => ({
  query: (query, cb) => cb('ee', null),
}));

Look that I'm not using any variables (const connection...) inside the jest.mock function

skyboyer

Also, I found out another solution thanks to @skyboyer.

Solution 2

Use names outside the jest.mock with the prefix mock*

const mockConnection = {
    query: (query, cb) => cb('ee', null),
}
jest.mock('./connection.js', 
Julian Mendez
  • 3,162
  • 2
  • 13
  • 36