import axios from 'axios'; import { mount } from 'enzyme'; import React from 'react'; import MyComponent from './MyComponent';
jest.mock('axios');
describe('MyComponent', () => { let wrapper; let axiosData = { data: { message: 'Hello' } };
beforeEach(async () => { axios.get.mockResolvedValue(axiosData);
wrapper = mount( );
});
afterEach(() => { jest.clearAllMocks(); });
it('Displays a message', () => { expect(wrapper.find('div').text()).toContain('Hello'); });
it('Calls axios.get with the correct url', () => { expect(axios.get).toHaveBeenCalledWith('http://example.com/my-api'); }); });
import axios from 'axios'; import sinon from 'sinon'; import { fetchUserData } from './user';
describe('fetchUserData', () => { it('should call axios and return success', async () => { const data = { data: { name: 'John Doe', email: 'john.doe@example.com' } };
const axiosStub = sinon.stub(axios, 'get').resolves(data);
const response = await fetchUserData();
expect(axiosStub.callCount).toBe(1);
expect(response).toEqual(data);
axios.get.restore();
});
it('should call axios and return error', async () => { const errorMsg = 'Request failed with status code 404'; const axiosStub = sinon.stub(axios, 'get').rejects(new Error(errorMsg));
try {
await fetchUserData();
} catch (error) {
expect(error).toEqual(new Error(errorMsg));
}
axios.get.restore();
}); });
下一篇:axios返回结果的测试结果