Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在jest中访问局部变量_Javascript_Unit Testing_Testing_Automated Tests_Jestjs - Fatal编程技术网

Javascript 如何在jest中访问局部变量

Javascript 如何在jest中访问局部变量,javascript,unit-testing,testing,automated-tests,jestjs,Javascript,Unit Testing,Testing,Automated Tests,Jestjs,目前,我正在尝试编写一个测试。我想在测试中使用局部变量,但不幸的是,我无法模拟或使用它。不导出变量和使用它的函数 如何访问utils.test.js中的局部变量authToken?所以我可以将authToken更改为另一个值 我尝试过使用rewre(),但没有成功。authToken仍未定义 utils.js const { auth } = require('./auth.js'); let authToken = undefined; const checkIfTokenIsValid

目前,我正在尝试编写一个测试。我想在测试中使用局部变量,但不幸的是,我无法模拟或使用它。不导出变量和使用它的函数

如何访问utils.test.js中的局部变量authToken?所以我可以将authToken更改为另一个值

我尝试过使用rewre(),但没有成功。authToken仍未定义

utils.js

const { auth } = require('./auth.js');

let authToken = undefined;

const checkIfTokenIsValid = async () => {
    if (authToken) {
        authToken = await auth();
    }
};

module.exports = {
    // some other functions
}
utils.test.js

const _rewire = require('rewire');
const utils = _rewire('../../lib/resources/utils');
utils.__set__('authToken', () => true);


describe('api auth', () => {
    // some tests
});

下面是使用模块的单元测试解决方案

utils.js

let{auth}=require('./auth');
让authToken=未定义;
const checkIfTokenIsValid=async()=>{
如果(authToken){
authToken=wait auth();
}
};
module.exports={
检查是否有效,
};
auth.js

异步函数auth(){
返回“真实身份验证响应”;
}
module.exports={auth};
utils.spec.js

const-rewre=require('rewre');
const-utils=重新布线('./utils');
描述('utils',()=>{
描述(#checkIfTokenIsValid',()=>{
测试('不应检查令牌',异步()=>{
const authMock=jest.fn();
实用程序集__({
auth:authMock,
authToken:未定义,
});
等待utils.checkIfTokenIsValid();
expect(authMock).not.toBeCalled();
});
测试('should check token',async()=>{
const authMock=jest.fn().mockResolvedValueOnce('abc');
实用程序集__({
auth:authMock,
authToken:123,
});
等待utils.checkIfTokenIsValid();
expect(authMock).toBeCalledTimes(1);
expect(utils.\uuu get.\uuuu('authToken')).toBe('abc');
});
});
});
单元测试结果:

PASS src/stackoverflow/57593767 todo/utils.spec.js
乌提尔斯
#checkIfTokenIsValid
✓ 不应检查令牌(7毫秒)
✓ 应检查令牌(2ms)
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个
时间:4.468秒
源代码: