这是我的动作,调用访存:
export const changeParameter = (parameter: ParameterName, value: any): ThunkAction => {
return async (
dispatch: ThunkDispatch<AppState, {}, ChangeParameterAction | ErrorAction>,
getState: () => AppState
) => {
const successMsg = `Parameter change succeeded: ${parameter} set to ${value}`;
const errorMsg = `Error attempting to set ${parameter} to ${value}`;
const url = 'http://example.com'
const state = getState();
const currentSettings = settingsApiPutPayload(state);
try {
const res = await fetch(url, {
method: 'PUT',
mode: 'cors',
headers: { 'Content-Type': 'application/json;charset=utf-8' },
body: JSON.stringify(currentSettings)
});
if (!res.ok) {
return dispatch(reportError('CHANGE_PARAMETER_FAILED', errorMsg));
}
console.log(successMsg);
dispatch({
type: 'CHANGE_PARAMETER', parameter, value: true
});
} catch (e) {
dispatch(reportError('CHANGE_PARAMETER_FAILED', errorMsg));
}
};
};
这是我的测试文件,使用fetch-mock
。
import {changeParameter} from "../index";
import thunk from "redux-thunk";
import configureMockStore from 'redux-mock-store';
import {ParameterName} from "../../types/redux.types";
import {defaultSettingsState} from "../../reducers/settings";
import fetchMock from "fetch-mock";
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('changeParameter', () => {
let spy: jest.SpyInstance;
let store;
beforeEach(() => {
spy = jest.spyOn(console, 'log').mockImplementation();
store = mockStore({ settings: defaultSettingsState });
});
afterEach(() => {
spy.mockReset();
});
it('should log a change to displayProgressIndicator', async () => {
// Arrange
let url = `http://example.com`;
fetchMock.mock('*', 200)
// Act
await store.dispatch(changeParameter(ParameterName.someParam, true));
// Assert
expect(fetchMock.called()).toEqual(true);
expect(spy).toHaveBeenCalledWith('Parameter change succeeded: someParam set to true');
});
});
第一个断言的测试失败了,我当然只是在第二个断言(我们关心的实际断言)失败之后才作为测试的结果。
如果我从测试代码本身执行访存,则该模拟有效。但是在实际的代码执行中,并没有模拟它。
我查看了fetch-mock
文档,它说如果您使用的是全局提取,则无需执行其他任何操作。在我的代码中,我仅调用fetch
而未导入任何内容,因此我认为这是全局的。
PS。我看了jest-fetch-mock
,我开始工作了,只是它看起来不像您可以指定匹配器,所以它要么模拟所有提取(或对任何东西一次提取),要么不模拟任何东西,这不似乎不太有用。