im trynna test my code, but it gives an error "TypeError: _react2.fireEvent.submit(...) is not a function", I dont know how to fix it, This error appears when i put the **"({ getByText, getByTestId, getByLabelText } = render(<TechList />)) "**, in the second test.
I need to test if the text "Node.js" stay in the component even when i rerender it.
My test code below:
import '#testing-library/jest-dom/extend-expect'
import React from 'react'
import { render, fireEvent } from '#testing-library/react'
import TechList from '../components/Techlist'
describe('TechList component', () => {
it('should be able to add new Tech', () => {
const { getByText, getByTestId, getByLabelText } = render(<TechList />)
fireEvent.change(getByLabelText('Tech'), { target: { value: 'Node.js' }})
fireEvent.submit(getByTestId('tech-form'))
expect(getByTestId('tech-list')).toContainElement(getByText('Node.js'))
expect(getByLabelText('Tech')).toHaveValue('')
})
it('should store techs in storage', () => {
let { getByText, getByTestId, getByLabelText} = render(<TechList />)
fireEvent.change(getByLabelText('Tech'), { target: { value: 'Node.js' }})
fireEvent.submit(getByTestId('tech-form'))
({ getByText, getByTestId, getByLabelText } = render(<TechList />))
expect(getByTestId('tech-list')).toContainElement(getByText('Node.js'))
})
})
and the Component:
import React, { useState } from 'react';
function Component() {
const [techs, setTechs] = useState([])
const [newTech, setNewTech] = useState('')
function handleAddTech() {
setTechs([...techs, 'Node.js'])
setNewTech('')
}
return (
<form data-testid="tech-form" onSubmit={handleAddTech} >
<ul data-testid="tech-list">
{techs.map(tech => <li key={tech}>{tech}</li>)}
</ul>
<label htmlFor="tech">Tech</label>
<input id="tech" type="text" value={newTech} onChange={e => setNewTech(e.target.value)}/>
<button type="submit" onClick={handleAddTech}>Adicionar</button>
</form>
)
}
export default Component;
In your second test code, the line ({ getByText, getByTestId, getByLabelText } = render(<TechList />)) is breaking it. Delete it and it should be working.
Related
Counter.test.js:
import Counter from 'components/Counter';
import { render, fireEvent } from '#testing-library/react';
import '#testing-library/jest-dom/extend-expect';
describe('Counter Testing', () => {
it('should pass', () => {
const { container } = render(<Counter></Counter>);
expect(container.querySelector('#count-value')).toHaveTextContent('0');
fireEvent.click(container.querySelector('#decrement-btn'));
expect(container.querySelector('#count-value')).toHaveTextContent('0');
});
});
Counter.js
import { useEffect, useState } from "react";
const Counter = props => {
const {count, setCount} = useState(0);
const handleIncrement = () =>{
count<10 ? setCount(count+1) :null;
}
const handleDecrement = () =>{
count>0 ? setCount(count-1) :null;
}
return (
<div>
Counter: <span id='count-value'>{count}</span>
<button onClick={handleIncrement} id='increment-btn'>+1</button>
<button onClick={handleDecrement} id='decrement-btn'>-1</button>
</div>
);
};
export default Counter;
Here i'm trying to test on clicking decerement button it should not go beyond 0. However i'm continuously returning error. Please find the below screen shot.
Any help is greatly appreciated. Thanks in Advance!
What I want to do
We have created hooks that communicate useMutation and switch the display when a button is clicked in a React component.
This test code is created using jest.
Occurring problems
Error: Uncaught [TypeError: Cannot read properties of undefined (reading '0')]
Source code in question
# Todo.jsx
import React, { useState } from 'react';
export const Todo = () => {
const [token, setToken] = useState('')
const [mutateFunction] = useMutation(CREATE_TOKEN);
const changeTodo = async (agreement) => {
const createTokenData = await mutateFunction();
if (createTokenData.data?.token === null) {
setToken('')
return;
}
setToken(createTokenData.data?.token)
}
};
return (
<div>
<button onClick={() => changeTodo(true)}>
Change Todo
</button>
</div>
)
};
# Todo.test.jsx
import React from 'react';
import { MockedProvider } from '#apollo/client/testing';
import { render, screen, fireEvent } from '#testing-library/react';
import { Todo } from 'Todo'
jest.mock('#apollo/client');
describe('Click the button', () => {
test('The value of token is null', async () => {
const mocks = [
{
request: {
query: CREATE_TOKEN,
},
result: {
data: {
createPcfToken: null
},
},
},
];
render(
<MockedProvider mocks={mocks} addTypename={false}>
<Todo />
</MockedProvider>
);
const button = screen.getByRole('button');
fireEvent.click(button);
});
});
What we tried
I am creating it while referring to the apollo official website, but I cannot receive data from mutateFunction.
I have tried everything but it just fails. What should I do?
Two mockImplementation solved the problem!
const mocks = {
{
data: {
token: null
},
};
}
const mockMutation = jest.fn()
(useMutation as jest.Mock).mockImplementation(() => [mockMutation]);
(mockMutation as jest.Mock).mockImplementation(() => mocks);
I have such function:
export const clearInput = (ref: RefObject<HTMLInputElement>) => {
if (null !== ref.current) {
ref.current.value = ''
}
};
I completely don't know how to test it in react-testing-library / jest.
This is my current code:
import React, { RefObject, useRef } from 'react'
import { clearInput, isInputTextMatch } from '../input';
import { fireEvent, render, waitForElement, } from '#testing-library/react'
import { debug } from 'console';
const Component = () => {
const inputRef = useRef<HTMLInputElement>(null);
return (
<input ref={inputRef} data-testid="Input" value="example" />
)
}
describe('clearInput helper', () => {
test('If used function, input value should be clear', async () => {
const { findByTestId } = render(<Component />);
const inputNode = await waitForElement(() =>
findByTestId('Input')
)
fireEvent.change(inputNode, {target: { value: ""}})
});
})
I have the following component
import React, { useState, useEffect } from 'react';
import { FiSearch } from 'react-icons/fi';
import { useProducts } from '../../hooks';
export default function SearchBar() {
const [query, setQuery] = useState('');
const [debounced, setDebounced] = useState('');
useEffect(() => {
const timeout = setTimeout(() => {
setDebounced(query);
}, 300);
return () => {
clearTimeout(timeout);
};
}, [query]);
const handleChange = (e) => {
e.preventDefault();
setQuery(e.target.value);
};
useProducts(debounced);
return (
<div className="search-form">
<FiSearch className="search-form__icon" />
<input
type="text"
className="search-form__input"
placeholder="Search for brands or shoes..."
onChange={handleChange}
value={query}
/>
</div>
);
}
I want to test if useProducts(debounced); is actually called 300ms later after typing. I sadly have no Idea where to begin and was hoping someone could help.
I'd recommend using #testing-library/user-event for typing on the <input> element, as it more closely simulates a user's triggered events.
As for the test, you should mock useProducts implementation to assert that it's called properly.
import React from 'react';
import { render, screen, waitFor } from '#testing-library/react';
import userEvent from '#testing-library/user-event';
import SearchBar from '<path-to-search-bar-component>'; // Update this accordingly
import * as hooks from '<path-to-hooks-file>'; // Update this accordingly
describe('Test <SearchBar />', () => {
it('should call useProducts after 300ms after typing', async () => {
const mockHook = jest.fn();
jest.spyOn(hooks, 'useProducts').mockImplementation(mockHook);
render(<SearchBar />);
const input = screen.getByPlaceholderText('Search for brands or shoes...');
userEvent.type(input, 'A');
expect(mockHook).not.toHaveBeenCalledWith('A'); // It won't be called immediately
await waitFor(() => expect(mockHook).toHaveBeenCalledWith('A'), { timeout: 350 }); // But will get called within 350ms
jest.clearAllMocks();
});
});
I'm relatively new to Jest and testing in general. I have a component with a text input element:
Here is my code snippet
<TextInput
testID="messageText"
ref={inputRef}
value={title}
onChangeText={(text) => {
setTitle(text)
}}
/>
Every time I am getting the error
Method “simulate” is meant to be run on 1 node. 2 found instead.
Here is my code --
const navigation = jest.fn()
const onChange = jest.fn();
const props = {
navigation: {
state: {
params: {
postType: 'text'
}
}
},
}
let wrapper
const event = {
target: {
value: 'This is just for test'
}
}
it('renders', () => {
wrapper = shallow(<NewFeedComponent {...props} />)
wrapper.find('Text').simulate('change', event)
expect(onChange).toHaveBeenCalledWith('This is just for test');
})
})
I created one sandbox so that you can understand more context. Just go through this sandbox(dont forget to run test runner to see actually test works):
code:
App.js
import React, { useState } from "react";
import "./styles.css";
export default function App(props) {
const [value, setValue] = useState("");
return (
<input
type={props.type}
value={value}
name="email"
className="basic-input"
placeholder={props.placeholder}
onChange={(e) => setValue(e.target.value)}
/>
);
}
App.test.js
import React from "react";
import ReactDOM from "react-dom";
import Adapter from "enzyme-adapter-react-16";
import { mount, shallow, configure } from "enzyme";
import App from "./App";
configure({ adapter: new Adapter() });
describe("basic input component", () => {
it("should renders without crashing", () => {
const div = document.createElement("div");
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
it("should render a placeholder", () => {
const placeholder_text = "type anything here";
const wrapper = shallow(<App placeholder={placeholder_text} />);
expect(wrapper.prop("placeholder")).toEqual(placeholder_text);
});
it("should render a correct type", () => {
const type = "password";
const wrapper = shallow(<App type={type} />);
expect(wrapper.prop("type")).toEqual(type);
});
it("should change the state after change the input value", () => {
const newValue = "testing component";
const wrapper = mount(<App value="" type="text" />);
// const input = wrapper.find('input[type="text"]');
wrapper
.find('input[name="email"]')
.simulate("change", { target: { value: newValue } });
expect(wrapper.find('input[name="email"]').prop("value")).toEqual(newValue);
});
});
Here is the demo: https://codesandbox.io/s/react-jest-enzyme-jn3ld?file=/src/App.js:0-360