如何使用Jest测试标头axios.defaults.headers?

时间:2020-10-27 23:01:06

标签: javascript reactjs axios jestjs http-headers

在我的应用程序中,我有一个中间件来检查req中的令牌以访问私有路由:

const config = require('../utils/config');
const jwt = require('jsonwebtoken');

module.exports = function (req, res, next) {
  let token = req.header('x-auth-token');

  if (!token) {
    return res.status(401).json({ msg: 'No token. Authorization DENIED.' });
  }

  try {
    let decoded = jwt.verify(token, config.JWTSECRET);
    req.user = decoded.user;
    next();
  } catch (err) {
    return res.status(401).json({ msg: 'Token is invalid.' });
  }
};

为了在程序的Redux操作中发送带有正确令牌的req,我调用以下函数setAuthToken()来设置auth令牌:

import axios from 'axios';

const setAuthToken = token => {
  if (token) {
    axios.defaults.headers.common['x-auth-token'] = token;
  } else {
    delete axios.defaults.headers.common['x-auth-token'];
  }
};

export default setAuthToken;

我使用axios和setAuthToken()函数执行Redux:

export const addPost = (formData) => async (dispatch) => {
  try {
    //set the token as the header to gain access to the protected route POST /api/posts
    if (localStorage.token) {
      setAuthToken(localStorage.token);
    }

    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    };

    const res = await axios.post('/api/posts', formData, config);

    // ...

  } catch (err) {
    // ...
  }
};

如何编写测试setAuthToken()的测试?以下是我的尝试:

import axios from 'axios';
import setAuthToken from '../../src/utils/setAuthToken';

describe('setAuthToken utility function.', () => {
    test('Sets the axios header, x-auth-token, with a token.', () => {
        let token = 'test token';

        setAuthToken(token);
        expect(axios.defaults.headers.common['x-auth-token']).toBe('test token');
    });
});

以下是我得到的错误:

TypeError: Cannot read property 'headers' of undefined

查找此错误,听起来好像是因为我的测试中没有req。如果是这种情况,我该如何重写测试以发送req?如果没有,我在做什么错了?

1 个答案:

答案 0 :(得分:1)

这是我的情况,我的项目中有一个__mocks__目录。有一个嘲笑的axios。有关__mocks__目录的更多信息,请参见Manual mock

__mocks__/axios.ts

const axiosMocked = {
  get: jest.fn()
};
export default axiosMocked;

当我运行您提供的测试时,出现与您相同的错误。因为模拟的axios对象没有defaults属性。这就是为什么出现错误。

import axios from 'axios';
import setAuthToken from './setAuthToken';

jest.unmock('axios');

describe('setAuthToken utility function.', () => {
  test('Sets the axios header, x-auth-token, with a token.', () => {
    let token = 'test token';
    setAuthToken(token);
    expect(axios.defaults.headers.common['x-auth-token']).toBe('test token');
  });
});

因此,我使用jest.unmock(moduleName)来使用实际的axios模块而不是模拟模块。

之后,它可以正常工作。单元测试结果:

 PASS  src/stackoverflow/64564148/setAuthToken.test.ts (10.913s)
  setAuthToken utility function.
    ✓ Sets the axios header, x-auth-token, with a token. (5ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.828s

另一个可能的原因是您启用了automock。检查命令和jest.config.js文件。