尝试在“ Nav”类中测试此功能,目的是测试Router,或更重要的是了解Router.push(/)
<AppBar className={classes.appBar} position="static">
<Toolbar className={classes.toolbar}>
{authenticated && this.state.layoutMode ==='desktop' ? (
<Grid container
direction ="row"
justify="flex-end"
alignItems="center">
<div className={classes.root}>
<Tabs id="Tab" className = {classes.tabBar} value={value} onChange={this.handleChange}>
<Tab label="example" alt="example" onClick={() => Router.push('/example')}/>
<Tab label="example" alt="example" onClick={() => Router.push('/example')}/>
<Tab label="example" alt="example" onClick={() => Router.push('/example')}/>
<Tab label="example" alt="example" onClick={() => Router.push('/example')}/>
<Tab label="example" alt="example" onClick={() => Router.push('/example')}/>
<Tab label="example" alt="example" onClick={() => Router.push('/example')}/>
</Tabs>
</div>
</Grid>
) : (
authenticated && <BurgerMenu/>
)}
到目前为止,我的测试看起来像这样
describe('Test for navigation', () => {
let sandbox;
beforeAll(() => {
sandbox = sinon.createSandbox();
});
afterEach(() => {
sandbox.restore();
});
it('should render with data', () => {
const stub = jest.fn();
sandbox.stub(Router, 'push').callsFake(stub);
const wrapper = shallow(<Nav authenticated />);
expect(wrapper).toMatchSnapshot();
expect(stub.mock.calls.length).toBe(0);
wrapper.find(AppBar).props().onClick('test');
expect(stub.mock.calls.length).toBe(7);
});
});
但是我遇到一个问题,我似乎找不到'AppBar'的属性,我已将Nav导入到测试中,但错误显示为“ Method“ props”应该在1个节点上运行。找到0个代替” 有什么想法吗?
答案 0 :(得分:0)
我认为问题在于您正试图在onClick
上调用AppBar
道具,但这是每个Tab
的道具。考虑到您要尝试覆盖更多内容,您应该像这样测试它:
让我们假设您的代码位于render函数中,并且id
道具对每个Tab
有效:
render(){
<AppBar className={classes.appBar} position="static">
<Toolbar className={classes.toolbar}>
{authenticated && this.state.layoutMode ==='desktop' ? (
<Grid container
direction ="row"
justify="flex-end"
alignItems="center">
<div className={classes.root}>
<Tabs id="Tab" className = {classes.tabBar} value={value} onChange={this.handleChange}>
<Tab id="Tab1" label="example" alt="example" onClick={() => Router.push('/example')}/>
<Tab id="Tab2" label="example" alt="example" onClick={() => Router.push('/example')}/>
<Tab id="Tab3" label="example" alt="example" onClick={() => Router.push('/example')}/>
<Tab id="Tab4" label="example" alt="example" onClick={() => Router.push('/example')}/>
<Tab id="Tab5" label="example" alt="example" onClick={() => Router.push('/example')}/>
<Tab id="Tab6" label="example" alt="example" onClick={() => Router.push('/example')}/>
</Tabs>
</div>
</Grid>
) : (
authenticated && <BurgerMenu/>
)}
</Toolbar>
</AppBar> }
现在让我们在测试中找到Tab1
:
it('should render with data', () => {
const stub = jest.fn();
sandbox.stub(Router, 'push').callsFake(stub);
const wrapper = shallow(<Nav authenticated />);
expect(wrapper).toMatchSnapshot();
expect(stub.mock.calls.length).toBe(0);
const tab1 = wrapper.find(`[id="Tab6"]`);
tab1.simulate("clic");
expect(stub.mock.calls.length).toBe(1);
});