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

问题描述 投票:0回答:1

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

如何访问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
});
javascript testing automated-tests jestjs
1个回答
0
投票

这里是使用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

© www.soinside.com 2019 - 2024. All rights reserved.