gpt4 book ai didi

unit-testing - 如何用 Jest 模拟导入

转载 作者:行者123 更新时间:2023-12-04 04:57:09 26 4
gpt4 key购买 nike

我有一个像这样的小型 redux 中间件

import { hashHistory } from 'react-router'
import { REDIRECT_TO_LOGIN_REDIRECT_URL } from '../actions/login-redirect';

export default store => next => action => {

if (action.type === REDIRECT_TO_LOGIN_REDIRECT_URL) {
hashHistory.push(store.getState().loginRedirectUrl);
}

return next(action)
}

我现在想测试一下。正如您在第 1 行中看到的,我正在导入 hashHistory 并在稍后使用它。这是我要测试的(对 hashHistory 的调用)。为此,我必须模拟 hashHistory,但我不知道如何模拟。我正在使用 jest:

import { REDIRECT_TO_LOGIN_REDIRECT_URL } from '../actions/login-redirect';
import redirectMiddleware from './redirect-after-login';

describe('redirect after login middleware', () => {

function setup() {
const store = {
subscribe: () => {},
dispatch: () => {},
getState: () => ({})
};
const next = jest.fn();
const action = { type: REDIRECT_TO_LOGIN_REDIRECT_URL };
return { store, next, action };
}

it('should push the redirect URL to the hashHistory', () => {
// How to test it?
})

});

最佳答案

你可以像这样模拟 react-router 模块:

import { hashHistory } from 'react-router'
import { REDIRECT_TO_LOGIN_REDIRECT_URL } from '../actions/login-redirect';
import redirectMiddleware from './redirect-after-login';

jest.mock('react-router', () => ({hashHistory: { push: jest.fn()}))

describe('redirect after login middleware', () => {
function setup() {
const store = {
subscribe: () => {},
dispatch: () => {},
getState: () => ({loginRedirectUrl: 'someLoginRedirectUrl'})
};
const next = jest.fn();
const action = { type: REDIRECT_TO_LOGIN_REDIRECT_URL };
return { store, next, action };
}

it('should push the redirect URL to the hashHistory', () => {
const { store, next, action } = setup()
redirectMiddleware(store)(next)(action)

expect(hashHistory.push).toHaveBeenCalledWith('someLoginRedirectUrl')
})
});

关于unit-testing - 如何用 Jest 模拟导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com