I need to test if delete button is present. The files structure are as below:
//a.js
import b from './b';
const xyz = props => {
const {var1, var2, func1, func2} = b(props);
return(
<Button buttonType='primary'onClick={func1}>Add</Button>
{
var2.length > 0 && <Button buttonType='negative' onClick={func2}>Remove</Button>
}) } export default xyz;
//b.js
const b= (props) => {
const { data } = props;
let [var1, setVar1] = useState(initialState);
let [var2, setVar2] = useState([]);
const func1 = async () => { //some data }
const func2 = async () => { //some data }
return { var1, var2, func1, func2}
}
export default b;
//a.spec.js
import xyz from './a';
import { render, fireEvent } from '@testing-library/react';
//I am trying to get delete button in this test case but it is failing because I couldn't mock the b file properly.
it('should display Delete button', () => {
const { getByRole } = render(<xyz sdk={mockSk.app}/>);
expect(getByRole('button', { name: 'Delete' })).toBeInTheDocument();
});
I am not certain how to mock b file so I can have some dummy value in var2 in return. it will satisfy the condition in a.js to display the delete button. the things that I have tried in test suites are :
const mockDeleteData = {
data: [{
userId: 1,
id: 1,
title: 'My First Album'
}]
}
let mockSk = {
app: {
onConfigure: jest.fn(),
getParameters: jest.fn().mockReturnValueOnce({}),
setReady: jest.fn(),
getCurrentState: jest.fn()
}
};
it('should display Delete button', () => {
1) jest.mock('./b'); //trying to mock b file but not sure how to assign dummy value to var2
//2) jest.spyOn(b, 'b.func1'); // trying random things to see if it is working.
3) b.mockResolvedValue({ // just checking if it returning this but it return undefined
data: [
{
userId: 1,
id: 1,
title: 'My First Album'
},
{
userId: 1,
id: 2,
title: 'Album: The Sequel'
}
]
});
4) b.default.var2 = mockDeleteData; // returns undefined instead of mockdata
5)const b= require('./b');
const handleClick = jest.spyOn(b, 'func1');
handleClick.mockReturnValue(mockDeleteData);
const { getByRole } = render(<xyz sdk={mockSk.app} />);
expect(getByRole('button', { name: 'Delete' })).toBeInTheDocument();
});
This pattern usually works for me.
import * as bModule from './b'
jest.spyOn(bModule, 'b').mockReturnValue(
(_props) => ({var1: value1, var2: value2, func1: jest.fn(), func2: jest.fn()}
)
You may not need to include var1, func1, or func2 in your mocked return object, if it doesn't cause your code to throw and you don't want to test them. You also don't need to include the _props input if you don't need that to set any return object.
I don't normally use export default, so you might first start with export const b = (props) => /*...*/ and see if you get that working first.