问题
I have the next get request:
const getReq = () => {
fetch(
'https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits',
)
.then((response) => {
let status = null;
if (response.status === 200) {
status = response.status;
} else {
status = 'error';
}
if (status === 200) {
alert('success')
} else {
alert('Error')
}
return response.json();
})
.then((commits) =>{
return commits.map(i=> i.sha[0])
});
};
getReq()
I want to make 3 tests for this request:
- if I get the first
sha
from commits:i=> i.sha[0]
- check for the 200 response
- check for the response that is not 200.
I wrote my first test:
import { getReq } from './getReq';
global.fetch = jest.fn(() => {
return Promise.resolve(123);
});
describe('success', () => {
test('get first sha http', async () => {
const sha = await getReq();
expect(sha).toBe(123);
});
});
But I get TypeError: Cannot read property 'then' of undefined
.
How to solve the issue with the test above?
回答1:
Your promise is not getting mock. You can try to adding this on the top of the file.
jest.mock(path_of_getReq_file, () => ({
getReq: jest.fn()
}));
来源:https://stackoverflow.com/questions/65037208/test-get-request-in-javascript