开玩笑地测试一个函数 javascript
testing a function in jest javascript
我有以下 onClick 函数
onClickFunction= index => () => {
this.setState({ activeIndex: index });
}
在下面的函数中用到了
getPersons= (persons) => persons
.map((person, index) => (
<StyledComponentHeader
key...
...
onClick={this.onClickFunction(index)}
>
<Styled2
...
>
{person.name}
</Styled2>
</StyledComponentHeader>
))
在我的单元测试中,我需要测试 onClickFunction
。目前我有这样的东西
const component= (
<StyledComponent
persons={persons}
/>);
describe('...', () => {
beforeEach(() => {
wrapper = shallow(component);
});
it('testing name', () => {
expect(wrapper).toMatchSnapshot();
expect(wrapper.state().activeIndex).toEqual(0);
wrapper.instance().onClickFunction(1);
expect(wrapper.state().activeIndex).toEqual(1);
});
它returns说上面的最后一个except
应该是0。测试这个函数的正确方法是什么?
因为 onClickFunction
不改变状态,但是 returns 一个函数,如果被调用然后改变状态,合乎逻辑的方法是用
来测试它
wrapper.instance().onClickFunction(1)();
(注意最后添加的()
调用返回的函数)
我有以下 onClick 函数
onClickFunction= index => () => {
this.setState({ activeIndex: index });
}
在下面的函数中用到了
getPersons= (persons) => persons
.map((person, index) => (
<StyledComponentHeader
key...
...
onClick={this.onClickFunction(index)}
>
<Styled2
...
>
{person.name}
</Styled2>
</StyledComponentHeader>
))
在我的单元测试中,我需要测试 onClickFunction
。目前我有这样的东西
const component= (
<StyledComponent
persons={persons}
/>);
describe('...', () => {
beforeEach(() => {
wrapper = shallow(component);
});
it('testing name', () => {
expect(wrapper).toMatchSnapshot();
expect(wrapper.state().activeIndex).toEqual(0);
wrapper.instance().onClickFunction(1);
expect(wrapper.state().activeIndex).toEqual(1);
});
它returns说上面的最后一个except
应该是0。测试这个函数的正确方法是什么?
因为 onClickFunction
不改变状态,但是 returns 一个函数,如果被调用然后改变状态,合乎逻辑的方法是用
wrapper.instance().onClickFunction(1)();
(注意最后添加的()
调用返回的函数)