Reputation: 21
I am not very familier yet on how to write unit tests via moxios and your help would be very much appreciated.
My request is the following:
export const walletRequest = () => {
return AWAxiosInstance()
.get(`${AW_BASE_URL}/account/wallet`)
.then(response => {
if (response) {
return formatAccountDetails(response.data);
}
})
.catch(error => {
return Promise.reject('Error requesting data from Account & Wallet API', error)
})
}
So basically here in the above function I'm trying to retrieve some data via an axios instance.
My understanding is that moxios is being used to mock the axios instance, but I am not very sure how to write the unit test for the walletRequest() function.
What I've tried:
import moxios from 'moxios'
import { walletRequest } from "../balance";
import AWAxiosInstance from '../../../../core/aw-axios-instance'
const responseMock = { balance: 100 };
describe("services/balance2", () => {
beforeEach(() => {
moxios.install(AWAxiosInstance)
})
afterEach(() => {
moxios.uninstall(AWAxiosInstance)
})
it("should call the walletRequest and retrieve data", () => {
moxios.wait(() => {
const request = moxios.requests.mostRecent()
request.respondWith({
status: 200,
response: {
responseMock
}
})
})
const response = walletRequest().response;
expect(response).toEqual(responseMock);
});
});
This doesn't work at this moment as the walletRequest() response is undefined. What can I do?
Thank you in advance!
Upvotes: 1
Views: 591
Reputation: 21
Solved this:
beforeEach(() => {
moxios.install(AWAxiosInstance)
formatAccountDetails.mockImplementation( () => responseMock)
})
afterEach(() => {
moxios.uninstall(AWAxiosInstance)
})
it("should return the data", async () => {
moxios.wait(() => {
const request = moxios.requests.mostRecent()
request.respondWith({
status: 200,
response: {
responseMock
}
})
})
const response = await walletRequest();
expect(response).toEqual(responseMock);
});
it('should not recieve response when request is rejected', () => {
const errorResp = {
status: 400,
response: { message: 'invalid data',
data: 'invalid data' }
};
const response = walletRequest();
moxios.wait(async() => {
let request = moxios.requests.mostRecent();
request.reject(errorResp);
response.then((err) => {
expect(err).toBe('invalid data');
});
});
});
Upvotes: 1