I am trying to assert that a function is called. Unfortunately it is passing unexpectedly - actually all assertions are. I believe that tests are finishing before everything is resolved.
export function callapi(input, setOptions, setSuggestStatus) {
if (input !== '') {
axios
.post(
requestURl,
{
input: `${input}`,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
},
{
credentials: 'include',
headers: {
'X-CSRF-Token': document && document.getElementsByTagName('body')[0].dataset.token,
},
},
)
.then(response => {
if (response.data.status === 'OK') {
const optionslist = response.data.suggestions.map(item => {
return { key: item.id};
});
// I need to assert that this function was called with options list
setOptions(optionslist);
}
})
.catch(e => {
console.log(e);
})
}
}
import axios from 'axios';
describe('callapi tests', () => {
it('should call setOptions with options when callapi is called', () => {
const updateFetchedData = jest.fn();
const response = {
data: {
status: 'OK',
suggestions: [{"id":1},{"id":2}]
}
}
const setOptions = jest.fn();
const expectedOptionsList = [
{
key: 1,
},
{
key: 2,
}
];
axios.post = jest.fn(() => {
return new Promise((resolve) => {
resolve(response);
// this should pass
expect(setOptions).toHaveBeenCalledWith(expectedOptionsList)
// this shouldn't pass but is
expect(1).toBe(2);
})
})
const setSuggestStatus = jest.fn();
callGoogleAutoCompleteSearch('input', setOptions, setSuggestStatus);
});
});
Right now all tests pass - obviously expect(1).toBe(2); should not pass. So all tests are passing even if they shouldn't. I think this is an async issue. Any help appreciated.