I am trying to write a test for my react bootstrap typeahead. On keyboard value enter, a HTTP .GET request should be made. In my test, when i enter values, my spy is never called.
Typeahead:
import React, { useState } from 'react';
import { render } from 'react-dom';
import './style.css';
import { AsyncTypeahead } from 'react-bootstrap-typeahead'; // ES2015
import 'react-bootstrap-typeahead/css/Typeahead.css';
import axios from 'axios';
export const Description = () => {
const [tyOptions, setOpts] = useState([]);
const handleSearch = (id) => {
axios
.get(`https://jsonplaceholder.typicode.com/todos/${id}`)
.then(({ options }) => {
console.log(options);
setOpts(options);
});
};
return (
<div>
<AsyncTypeahead
id="test"
labelKey="title"
minLength={1}
onSearch={handleSearch}
options={tyOptions}
placeholder="Search todo by id."
renderMenuItemChildren={(option) => (
<>
<span>
Test
</span>
</>
)}
/>
</div>
);
};
Test:
describe("App Component Testing", () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should get typeahead data', async () => {
let axios = jest.spyOn(axios, 'get').mockReturnValue(Promise.resolve(
{
data: [1, 2, 3, 4, 5]
}
));
let component;
await act(async () => {
component = render(<Description/>);
});
let inputEl = component.queryByPlaceholderText(/Search todo by id./);
userEvent.click(inputEl);
userEvent.type(inputEl, 'test val');
expect(axios.get).toHaveBeenCalled();
});
});
Error:
expect(jest.fn()).toHaveBeenCalled();
Expected number of calls: => 1
Received number of calls: 0