Javascript ReactJS:如何测试组件功能?
在我的meteor应用程序中,我通过测试我使用的所有方法来进行一些单元测试。我正在这样做测试(摩卡/柴):Javascript ReactJS:如何测试组件功能?,javascript,reactjs,unit-testing,meteor,chai,Javascript,Reactjs,Unit Testing,Meteor,Chai,在我的meteor应用程序中,我通过测试我使用的所有方法来进行一些单元测试。我正在这样做测试(摩卡/柴): describe('postMessage', () => { it('should add message', (done) => { // EXECUTE const messageId = postMessage.call({ articleId: 123, content: 'Message text' }) // VERIFY co
describe('postMessage', () => {
it('should add message', (done) => {
// EXECUTE
const messageId = postMessage.call({ articleId: 123, content: 'Message text' })
// VERIFY
const message = Messenger.findOne(messageId) // get data from mongoDB
expect(message.content).to.equal('Message text') // check for message
expect(message.articleId).to.be.equal(123) // check for articleId
done()
})
})
但是只有一部分被测试,它将消息存储到数据库中。但我还必须测试编写消息并提交(模糊事件)是否会调用此方法
这就是我的组件的外观。我需要知道如何对这个组件进行测试。因此,在本例中,我需要测试方法postMessage
是否在textarea元素的blur事件上调用,以及result
的状态值是否获取ID。我该如何做
组件
class Message extends Component {
addPost (articleId, event) {
const content = event.target.value
postMessage.call(
{ content, articleId },
(error, result) => {
if (error) console.warn(error)
if (result) this.setState({ result })
}
)
}
render () {
return (
<Form>
<TextArea onBlur={this.addPost.bind(this, articleId)} />
</Form>
)
}
}
如果必须对此进行测试,可以使用forTextArea
手动触发模糊事件。您还应该能够存根消息#addPost
,以验证是否确实在blur上调用了is
尽管如此,我必须指出,这不是一个特别有价值的测试。您已经测试了addPost
是否按预期工作。通过测试在blur上调用addPost
,您正在测试两件事:
- React正确处理事件
- 您将函数传递给
,而不是简单地执行函数(对于较新的javascript开发人员来说,这是一个容易犯的错误)onBlur
在我看来,这两项都不是特别有价值的测试。也许
酶+sinon
可以帮助你。除了addPost
测试之外,我还将保持blur
行为测试,这将使维护更容易,阅读更简单
import { shallow } from 'enzyme';
import sinon from 'sinon';
describe('...', () => {
it('Calls Message.addPost function when TextArea.onBlur', () => {
// prepare mock and renders
Message.addPost = sinon.spy();
const wrapper = shallow(<Message />);
const textArea = wrapper.find(TextArea)
// simulate user action
textArea.simulate('blur');
// assert expected outcome
expect(Message.addPost.calledOnce).to.equal(true);
});
})
import{shall}来自“酶”;
从“sinon”进口sinon;
描述(“…”,()=>{
它('当TextArea.onBlur'时调用Message.addPost函数,()=>{
//准备模拟和渲染
Message.addPost=sinon.spy();
常量包装器=浅();
const textArea=wrapper.find(textArea)
//模拟用户操作
textArea.simulate('blur');
//断言预期结果
expect(Message.addPost.calledOnce).to.equal(true);
});
})
import { shallow } from 'enzyme';
import sinon from 'sinon';
describe('...', () => {
it('Calls Message.addPost function when TextArea.onBlur', () => {
// prepare mock and renders
Message.addPost = sinon.spy();
const wrapper = shallow(<Message />);
const textArea = wrapper.find(TextArea)
// simulate user action
textArea.simulate('blur');
// assert expected outcome
expect(Message.addPost.calledOnce).to.equal(true);
});
})