javascript - 如何在 Jest 中访问局部变量

标签 javascript unit-testing testing automated-tests jestjs

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

如何访问 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/

相关文章:

javascript - Mosync Javascript NativeUI 编辑框作为密码字段

java - Swing UI 测试库比较 : FEST, WindowTester Pro 等

Java代码覆盖率: method level unit test

Maven Spring 测试中的 springTestContextBeforeTestMethod 失败

javascript - 如何知道何时加载特定 "div"内的所有图像?

javascript - Azure 功能 CORS 配置与 SignalR 服务不起作用

javascript - React Router 和历史

java - 减少测试用例之间的耦合

python - python测试中的函数调用列表

vue.js - 无法窥探原始值;给定的未定义。 Vue JS、Jest、实用程序