简体   繁体   English

如何对SAPUI5控件的onBendering进行单元测试?

[英]How to unit test onBeforeRendering of SAPUI5 control?

Let's assume that I have the following code: 我们假设我有以下代码:

var title = new sap.m.Title();
title.addEventDelegate({
    onBeforeRendering: jQuery.proxy(function () {
        title.setText(this._createTitleText());
    }, this)
});

which sets the text to the title only on before rendering. 它仅在渲染之前将文本设置为title

The question is how to unit test this ? 问题是如何对此进行单元测试

As I understand SAPUI5 framework will fire this event and then I should be able to attach to it and verify that the text of the title is correct, but how to do it and is it a right way? 据我所知SAPUI5框架将触发此事件,然后我应该能够附加到它并验证标题的文本是否正确,但如何做到这是正确的方法?

This is what I was trying, but at least I don't get any text from my control plus for me it is not clear which data I should pass to this method. 这就是我的尝试,但至少我没有从我的控制中得到任何文本加上对我来说不清楚我应该传递给这个方法的数据。

title.attachBeforeRendering("data", function (oEvent) {
    var text = title.getText();
});

I found the following way: 我发现了以下方式:

title.addEventDelegate({
    onBeforeRendering: jQuery.proxy(function () {
        assert.equal(title.getText(), expectedTitle, "Title has correct text");
    }, this)
});

However, this is not enough because onBeforeRendering will happen after the test which means that it depends on the time thus it is not sure if it is going to happen. 但是,这还不够,因为onBeforeRendering将在测试后发生,这意味着它取决于时间,因此不确定它是否会发生。 But there is a way to make it for sure: 但有一种方法可以肯定:

In the end of the test we should call: 在测试结束时我们应该致电:

return new Promise(function (resolve, reject) {
    setTimeout(function () {
        QUnit.start();
    }, 100);
});

which will cover our case plus continue executing to another unit test. 这将涵盖我们的情况加上继续执行另一个单元测试。

You can try to call onAfterRendering manually or just invalidate or rerender the control. 您可以尝试手动调用onAfterRendering,或者只是使控件无效或重新呈现。

Try to do something like 尝试做类似的事情

// act
oTitle.onAfterRendering();

// assert
assert.strictEqual(oTitle.getTitle(), "__expected_title__", "Title is correct!");

In case you are just testing if the title is changed. 如果您只是测试标题是否更改。 I would prefer to stub the setTitle method and check if it is called with a correct parameter. 我宁愿存根setTitle方法并检查它是否使用正确的参数调用。

You can see that usually events are tested in this way eg https://github.com/SAP/openui5/blob/master/src/sap.m/test/sap/m/qunit/MultiComboBox.qunit.html#L4479 您可以看到通常以这种方式测试事件,例如https://github.com/SAP/openui5/blob/master/src/sap.m/test/sap/m/qunit/MultiComboBox.qunit.html#L4479

In your case you don't need a fake event, but it is quite similar. 在您的情况下,您不需要假事件,但它非常相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM