目前,我正在尝试编写一个测试。我想在测试中使用局部变量,但不幸的是,我无法模拟或使用它。变量和使用它的函数不会导出。
如何访问 utils.test.js 中的局部变量 authToken?所以我可以将 authToken 更改为另一个值。
我尝试使用重新接线( https://www.npmjs.com/package/rewire ),但这不起作用。 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
});
最佳答案
这是使用 rewire 的单元测试解决方案模块。
utils.js
:
let { auth } = require('./auth');
let authToken = undefined;
const checkIfTokenIsValid = async () => {
if (authToken) {
authToken = await auth();
}
};
module.exports = {
checkIfTokenIsValid,
};
auth.js
:
async function auth() {
return 'real auth response';
}
module.exports = { auth };
utils.spec.js
:
const rewire = require('rewire');
const utils = rewire('./utils');
describe('utils', () => {
describe('#checkIfTokenIsValid', () => {
test('should not check token', async () => {
const authMock = jest.fn();
utils.__set__({
auth: authMock,
authToken: undefined,
});
await utils.checkIfTokenIsValid();
expect(authMock).not.toBeCalled();
});
test('should check token', async () => {
const authMock = jest.fn().mockResolvedValueOnce('abc');
utils.__set__({
auth: authMock,
authToken: 123,
});
await utils.checkIfTokenIsValid();
expect(authMock).toBeCalledTimes(1);
expect(utils.__get__('authToken')).toBe('abc');
});
});
});
单元测试结果:
PASS src/stackoverflow/57593767-todo/utils.spec.js
utils
#checkIfTokenIsValid
✓ should not check token (7ms)
✓ should check token (2ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 4.468s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57593767
关于javascript - 如何在 Jest 中访问局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57593767/