我是在对进行了大量研究后问这个问题的
我有这些文件
// 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;
当我用笑话做什么测试时(删除不必要的东西以更好地阅读(
// 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
});
我得到下一个错误
The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
Invalid variable access: connection
我试着移动同一文件夹中的文件,有相对路径,绝对路径,移动导入的顺序,但我真的做不到
我真的不知道如何解决这个问题,而且我正在从proxyquire迁移到笑话,这就是我这样做的原因,我不能再使用proxyquire了。
是的,嗯。。。我会为未来回答我自己的问题。
问题是,您不能像我所做的那样使用在jest.mock()
函数外部声明的变量。
测试文件和mock函数应该类似于
解决方案1
jest.mock('./connection.js', () => ({
query: (query, cb) => cb('ee', null),
}));
注意,我没有在jest.mock
函数中使用任何变量(const connection...
(
skyboyer
此外,多亏@skyboyer,我找到了另一个解决方案。
解决方案2
使用前缀为mock*
的jest.mock
之外的名称
const mockConnection = {
query: (query, cb) => cb('ee', null),
}
jest.mock('./connection.js',