我正在学习React,目前正在尝试开玩笑/测试。我正在一个小项目上开始测试,我想获得100%的代码覆盖率。这就是我所拥有的。
组件:
import React from 'react';
function Square(props) {
const className = props.isWinningSquare ?
"square winning-square" :
"square";
return (
<button
className={className}
onClick={() => props.onClick()}
>
{props.value}
</button>
);
}
export default Square
测试:
import React from 'react';
import Square from '../square';
import {create} from 'react-test-renderer';
describe('Square Simple Snapshot Test', () => {
test('Testing square', () => {
let tree = create(<Square />);
expect(tree.toJSON()).toMatchSnapshot();
})
})
describe('Square className is affected by isWinningSquare prop', () => {
test('props.isWinningSquare is false, className should be "square"', () =>{
let tree = create(<Square isWinningSquare={false} />);
expect(tree.root.findByType('button').props.className).toEqual('square');
}),
test('props.isWinningSquare is true, className should be "square winning-square"', () =>{
let tree = create(<Square isWinningSquare={true} />);
expect(tree.root.findByType('button').props.className).toEqual('square winning-square');
})
})
表示为“未发现”的行是
onClick={() => props.onClick()}
测试此行的最佳方法是什么?有什么建议吗?
答案 0 :(得分:3)
您将使用Mock Function
test('props.onClick is called when button is clicked', () =>{
const fn = jest.fn();
let tree = create(<Square onClick={fn} />);
// Simulate button click
const button = tree.root.findByType('button'):
button.props.onClick()
// Verify callback is invoked
expect(fn.mock.calls.length).toBe(1);
});
此外,就其价值而言,您可以在组件中将onClick
处理函数直接分配给道具,即
<button
className={className}
onClick={props.onClick}
>
答案 1 :(得分:0)
只需将元素作为目标并调用其处理程序:
val navController = Navigation.findNavController(requireActivity(), R.id.nav_tabs_home)
val bottomNavBar: BottomNavigationView = nav_content_view
NavigationUI.setupWithNavController(bottomNavBar, navController)