如何在玩笑中访问局部变量

f4z*_*4zr 2 javascript testing automated-tests unit-testing jestjs

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

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

我尝试使用重新接线(https://www.npmjs.com/package/rewire),但这不起作用。authToken 仍未定义。

实用程序.js

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

let authToken = undefined;

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

module.exports = {
    // some other functions
}
Run Code Online (Sandbox Code Playgroud)

utils.test.js

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


describe('api auth', () => {
    // some tests
});
Run Code Online (Sandbox Code Playgroud)

sli*_*wp2 5

这是使用rewire模块的单元测试解决方案。

\n\n

utils.js:

\n\n
let { auth } = require(\'./auth\');\n\nlet authToken = undefined;\n\nconst checkIfTokenIsValid = async () => {\n  if (authToken) {\n    authToken = await auth();\n  }\n};\n\nmodule.exports = {\n  checkIfTokenIsValid,\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

auth.js:

\n\n
async function auth() {\n  return \'real auth response\';\n}\nmodule.exports = { auth };\n
Run Code Online (Sandbox Code Playgroud)\n\n

utils.spec.js:

\n\n
const rewire = require(\'rewire\');\nconst utils = rewire(\'./utils\');\n\ndescribe(\'utils\', () => {\n  describe(\'#checkIfTokenIsValid\', () => {\n    test(\'should not check token\', async () => {\n      const authMock = jest.fn();\n      utils.__set__({\n        auth: authMock,\n        authToken: undefined,\n      });\n      await utils.checkIfTokenIsValid();\n      expect(authMock).not.toBeCalled();\n    });\n\n    test(\'should check token\', async () => {\n      const authMock = jest.fn().mockResolvedValueOnce(\'abc\');\n      utils.__set__({\n        auth: authMock,\n        authToken: 123,\n      });\n      await utils.checkIfTokenIsValid();\n      expect(authMock).toBeCalledTimes(1);\n      expect(utils.__get__(\'authToken\')).toBe(\'abc\');\n    });\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

单元测试结果:

\n\n
 PASS  src/stackoverflow/57593767-todo/utils.spec.js\n  utils\n    #checkIfTokenIsValid\n      \xe2\x9c\x93 should not check token (7ms)\n      \xe2\x9c\x93 should check token (2ms)\n\nTest Suites: 1 passed, 1 total\nTests:       2 passed, 2 total\nSnapshots:   0 total\nTime:        4.468s\n
Run Code Online (Sandbox Code Playgroud)\n\n

源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57593767

\n