![](/img/trans.png)
[英]testing-library react mock function with callback that will set state on return
[英]mock export function and variable in react testing library
我需要测试是否存在删除按钮。 文件结构如下:
//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();
});
我不确定如何模拟 b 文件,所以我可以在 var2 中有一些虚拟值作为回报。 它将满足 a.js 中的条件以显示删除按钮。 我在测试套件中尝试过的事情是:
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('应该显示删除按钮', () => {
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();
});
这种模式通常对我有用。
import * as bModule from './b'
jest.spyOn(bModule, 'b').mockReturnValue(
(_props) => ({var1: value1, var2: value2, func1: jest.fn(), func2: jest.fn()}
)
你可能不需要在你的模拟返回对象中包含var1
、 func1
或func2
,如果它不会导致你的代码抛出并且你不想测试它们。 如果您不需要设置任何返回对象,则也不需要包含_props
输入。
我通常不使用export default
,所以你可能首先从export const b = (props) => /*...*/
,看看你是否先开始工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.