mock inner axios.create()
사용하고 있다jest
그리고.axios-mock-adapter
시험하다axios
API 호출redux
비동기 액션크리에이터
사용 중에는 동작시킬 수 없습니다.axios
로 작성된 인스턴스axios.create()
다음과 같이 합니다.
import axios from 'axios';
const { REACT_APP_BASE_URL } = process.env;
export const ajax = axios.create({
baseURL: REACT_APP_BASE_URL,
});
그걸 소비할 수 있을 것 같아요.async action creator
예를 들어 다음과 같습니다.
import { ajax } from '../../api/Ajax'
export function reportGet(data) {
return async (dispatch, getState) => {
dispatch({ type: REQUEST_TRANSACTION_DATA })
try {
const result = await ajax.post(
END_POINT_MERCHANT_TRANSACTIONS_GET,
data,
)
dispatch({ type: RECEIVE_TRANSACTION_DATA, data: result.data })
return result.data
} catch (e) {
throw new Error(e);
}
}
}
테스트 파일은 다음과 같습니다.
import {
reportGet,
REQUEST_TRANSACTION_DATA,
RECEIVE_TRANSACTION_DATA,
} from '../redux/TransactionRedux'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import { END_POINT_MERCHANT_TRANSACTIONS_GET } from 'src/utils/apiHandler'
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const store = mockStore({ transactions: {} })
test('get report data', async () => {
let mock = new MockAdapter(axios)
const mockData = {
totalSalesAmount: 0
}
mock.onPost(END_POINT_MERCHANT_TRANSACTIONS_GET).reply(200, mockData)
const expectedActions = [
{ type: REQUEST_TRANSACTION_DATA },
{ type: RECEIVE_TRANSACTION_DATA, data: mockData },
]
await store.dispatch(reportGet())
expect(store.getActions()).toEqual(expectedActions)
})
그리고 나는 오직 한 가지 액션만 받는다.Received: [{"type": "REQUEST_TRANSACTION_DATA"}]
에러가 났기 때문입니다.ajax.post
.
나는 많은 방법으로 조롱해 왔다.axios.create
내가 뭘 하고 있는지 모르고서는 아무 소용이 없어.모든 도움에 감사드립니다.
네, 알았어요.이렇게 고쳤어요!나는 결국 도서관들을 비웃지 않고 하게 되었다.axios
!
에 대한 모의 작성axios
에src/__mocks__
:
// src/__mocks__/axios.ts
const mockAxios = jest.genMockFromModule('axios')
// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios)
export default mockAxios
테스트 파일의 요지는 다음과 같습니다.
import mockAxios from 'axios'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
// for some reason i need this to fix reducer keys undefined errors..
jest.mock('../../store/rootStore.ts')
// you need the 'async'!
test('Retrieve transaction data based on a date range', async () => {
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const store = mockStore()
const mockData = {
'data': 123
}
/**
* SETUP
* This is where you override the 'post' method of your mocked axios and return
* mocked data in an appropriate data structure-- {data: YOUR_DATA} -- which
* mirrors the actual API call, in this case, the 'reportGet'
*/
mockAxios.post.mockImplementationOnce(() =>
Promise.resolve({ data: mockData }),
)
const expectedActions = [
{ type: REQUEST_TRANSACTION_DATA },
{ type: RECEIVE_TRANSACTION_DATA, data: mockData },
]
// work
await store.dispatch(reportGet())
// assertions / expects
expect(store.getActions()).toEqual(expectedActions)
expect(mockAxios.post).toHaveBeenCalledTimes(1)
})
Jest 테스트를 작성해야 하는 경우axios
와 함께create
특정 테스트(다른 답변에서 언급한 것처럼 모든 테스트 사례에 대해 모의 공리가 필요하지 않음)에서는 다음을 사용할 수도 있습니다.
const axios = require("axios");
jest.mock("axios");
beforeAll(() => {
axios.create.mockReturnThis();
});
test('should fetch users', () => {
const users = [{name: 'Bob'}];
const resp = {data: users};
axios.get.mockResolvedValue(resp);
// or you could use the following depending on your use case:
// axios.get.mockImplementation(() => Promise.resolve(resp))
return Users.all().then(data => expect(data).toEqual(users));
});
여기 악시오스가 Jest에서 조롱하는 같은 예에 대한 링크가 있습니다.create
다른 점은 다음과 같습니다.axios.create.mockReturnThis()
여기 공리에 대한 나의 조롱이 있다.
export default {
defaults:{
headers:{
common:{
"Content-Type":"",
"Authorization":""
}
}
},
get: jest.fn(() => Promise.resolve({ data: {} })),
post: jest.fn(() => Promise.resolve({ data: {} })),
put: jest.fn(() => Promise.resolve({ data: {} })),
delete: jest.fn(() => Promise.resolve({ data: {} })),
create: jest.fn(function () {
return {
interceptors:{
request : {
use: jest.fn(() => Promise.resolve({ data: {} })),
}
},
defaults:{
headers:{
common:{
"Content-Type":"",
"Authorization":""
}
}
},
get: jest.fn(() => Promise.resolve({ data: {} })),
post: jest.fn(() => Promise.resolve({ data: {} })),
put: jest.fn(() => Promise.resolve({ data: {} })),
delete: jest.fn(() => Promise.resolve({ data: {} })),
}
}),
};
mockAdapter에서는 잘못된 사례를 조롱하고 있습니다.대신 에이잭스를 조롱했어야지이것처럼.const mock = MockAdapter(ajax)
이것은 당신이 지금 조롱하지 않고 있기 때문입니다.axios
일례라기보다는 오히려ajax
요청을 전송하기 위해 사용하는 것이기 때문에, 즉, 요청을 전송할 때 axios 인스턴스를 생성했습니다.export const ajax = axios.create...
그래서 네가 하고 있으니까const result = await ajax.post
당신의 코드에 따르면ajax
조롱해야 할 공리의 예axios
그런 경우에는요.
다른 해결책이 있어요.
import {
reportGet,
REQUEST_TRANSACTION_DATA,
RECEIVE_TRANSACTION_DATA,
} from '../redux/TransactionRedux'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import { END_POINT_MERCHANT_TRANSACTIONS_GET } from 'src/utils/apiHandler'
// import axios from 'axios'
import { ajax } from '../../api/Ajax' // axios instance
import MockAdapter from 'axios-mock-adapter'
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const store = mockStore({ transactions: {} })
test('get report data', async () => {
// let mock = new MockAdapter(axios)
let mock = new MockAdapter(ajax) // this here need to mock axios instance
const mockData = {
totalSalesAmount: 0
}
mock.onPost(END_POINT_MERCHANT_TRANSACTIONS_GET).reply(200, mockData)
const expectedActions = [
{ type: REQUEST_TRANSACTION_DATA },
{ type: RECEIVE_TRANSACTION_DATA, data: mockData },
]
await store.dispatch(reportGet())
expect(store.getActions()).toEqual(expectedActions)
})
다른 방법: 이 파일을 에 추가합니다.src/__mocks__
폴더
import { AxiosStatic } from 'axios';
const axiosMock = jest.createMockFromModule<AxiosStatic>('axios');
axiosMock.create = jest.fn(() => axiosMock);
export default axiosMock;
다음 코드가 작동합니다!
jest.mock("axios", () => {
return {
create: jest.fn(() => axios),
post: jest.fn(() => Promise.resolve()),
};
});
언급URL : https://stackoverflow.com/questions/51393952/mock-inner-axios-create
'programing' 카테고리의 다른 글
UI 선택에서 수동으로 입력한 텍스트 허용 (0) | 2023.03.18 |
---|---|
Python 직렬화 가능 개체 json (0) | 2023.03.18 |
React 컴포넌트가 재렌더되는 이유를 추적 (0) | 2023.03.18 |
this.setState가 예상대로 상태를 Marge하지 않습니다. (0) | 2023.03.13 |
상대 templateUrl을 로드하는 중 (0) | 2023.03.13 |