【问题标题】:JEST Invalid variable access mocking inside constJEST const 内的无效变量访问模拟
【发布时间】:2020-07-28 23:44:20
【问题描述】:

经过大量研究,我问这个问题

我有这些文件

// 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 迁移到 jest,这就是我这样做的原因,我不能再使用 proxyquire。

【问题讨论】:

标签: jestjs


【解决方案1】:

是的,嗯... 将来会回答我自己的问题。

问题是你不能像我一样使用在jest.mock() 函数之外声明的变量。

测试文件和mock函数应该是这样的

解决方案 1

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

看我在jest.mock 函数中没有使用任何变量(const connection...

天空男孩

另外,感谢@skyboyer,我找到了另一个解决方案。

解决方案 2

使用jest.mock 之外的名称,前缀为mock*

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

【讨论】:

    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 2021-10-09
    • 2021-09-21
    相关资源
    最近更新 更多