尝试使用Karma + Jasmine测试React组件,
我试图检查调用所有函数到 <StackPanel Orientation="Horizontal">
<Button Width="100" Content="Foo" Click="Button_Click"/>
<Button Width="100" Content="Bar" Click="Button_Click"/>
<Button Width="100" Content="Baz" Click="Button_Click"/>
</StackPanel>
<!-- set the width to 300 -->
<ListBox Grid.Row="1" Name="TheList" Height="100" Width="300" />
处理程序,但测试返回false结果:
onClick
这是我的组件:
`Expected spy reportLoginWithEmail to have been called.`
signInWithEmail处理程序:
<a className="sign-in-with-email" onClick={this.signInWithEmail}>
Or Sign in with your Email
</a>
测试:
signInWithEmail = (event) => {
event.preventDefault();
this.setState({
isEmailSignIn: true
});
biActions.reportLoginWithEmail();
};
另一方面, describe('SignIn', () => {
let component, biActions;
beforeEach(() => {
component = TestUtils.renderIntoDocument(<SignIn/>);
biActions = require('../../../actions/BIActions');
spyOn(biActions, 'reportLoginWithEmail');
});
it('test clicking on login by email call function', () => {
let signInEmail = TestUtils.findRenderedDOMComponentWithClass(component, 'sign-in-with-email');
TestUtils.Simulate.click(signInEmail);
expect(biActions.reportLoginWithEmail).toHaveBeenCalled();
});
});
的测试更改了返回state
:
true
我缺少什么,有什么建议吗?
答案 0 :(得分:1)
好的,经过几个小时的研究后我发现了问题:
require
您的组件顺序非常重要,这是我的问题。
导入测试SignIn
组件的顶部:
import SignIn from '../components/SignIn;
并且仅在mock
已reportLoginWithEmail
组件已初始化的beforeEach
SignIn
之后,it
阻止检查mock
是否为SignIn
在mock
组件调用非require
'ed函数
因此问题已通过import
的更改顺序得到解决,并在测试,工作代码顶部删除了SignIn
个beforeEach(() => {
biActions = require('../../../actions/BIActions');
spyOn(biActions, 'reportLoginWithEmail');
SignIn = require('../../../components/LoginPage/SignIn');
LoginByEmail = require('../../../components/LoginPage/LoginByEmail');
component = TestUtils.renderIntoDocument(<SignIn/>);
});
组件:
SignIn
在这种情况下使用mock
'ed reportLoginWithEmail
函数初始化 JPanel panelGraph = new JPanel();
panelGraph.setBounds(220, 64, 329, 250);
panelMain.add(panelGraph); //it is inside the main panel
panelGraph.setLayout(null);
组件