当用jest和酶测试时,没有传递给axios.interceptor的新道具

时间:2018-01-27 20:00:42

标签: reactjs react-router axios enzyme jest

我在测试时遇到问题,看看我的axios.intercepters是否会推送到401上的登录页面。我的代码正在触及拦截器,但由于this.props.location.pathname未被更新,我不会通过我的if语句wrapper.setProps({ location: { pathname: '/dashboard' } })

来自AppContainer的相关代码

componentWillMount = async () => {
  axios.interceptors.response.use(
    response => response,
    error => (
      error.response.status === 401 && this.props.location.pathname !== '/'
        ? this.props.history.push('/account/login')
        : error
    ),
  );

  const { data } = await Account.auth();
  this.setState({ isAuth: data.isAuth });
}

我的测试中的相关代码

describe('AppContainer', () => {
let wrapper = null;
let instance = null;

const mockProps = {
  history: { push: jest.fn(), replace: jest.fn() },
  location: { pathname: '/' },
};

beforeEach(() => {
  mock.reset();
  mock.onGet('/api/account/auth').reply(200, { isAuth: true });
  wrapper = shallow(<AppContainer {...mockProps} />);
  instance = wrapper.instance();
});

it('should redirect to /account/login if api calls error 401 and location is not "/"', async () => {
  mock.onGet('/mockCall').reply(401);
  wrapper.setProps({ location: { pathname: '/dashboard' } });
  instance.mockCall = () => axios.get('/mockCall');

  await instance.mockCall();
  expect(instance.props.history.push).toHaveBeenLastCalledWith('/account/login');
});

记录componentWillReceiveProps(nextProps)内部显示this.props.location.pathname = '/dashboard'但是在axios.interceptor上我的错误函数内部的日志记录显示了之前的道具,而不是新的道具。 我的期望toHaveBeenLastCalledWith('/account/login')表明它根本没有被调用

我的拦截器是否在错误的位置?

0 个答案:

没有答案