【问题标题】:Karate: How to use a Javascript function from a DIFFERENT feature file空手道:如何使用来自不同功能文件的 Javascript 函数
【发布时间】:2018-05-07 16:28:35
【问题描述】:

我创建了一个包含大量 javascript 函数的功能文件。

在不同的功能文件中,我想使用其中一个功能(并传入一个值)。

请问我该怎么做?

我的功能文件名为 SystemSolentraCustomKarateMethods.feature

这是当前内容(目前只包含一个函数):

Feature: System Solentra Status Test

Background:

* def checkreturneddatetimeiscorrect =

#The following code compares the passed in datetime with the current systemdatetime and
#makes sure they are within 2 seconds of each other

"""
function(datetime) {

var datenow = new Date();
karate.log("***The Date Now  = " + datenow.toISOString() + " ***");
var timenow = datenow.getTime();
karate.log("***The Time Now in Milliseconds  = " + timenow+ " ***");


karate.log("***The Passedin Date  = " + datetime + " ***");
var passedintime = new Date();
passedintime = Date.parse(datetime);
karate.log("***The Passed in Time = " + passedintime+ " ***");

var difference = timenow - passedintime;
karate.log("***The Time Difference = " + difference + " milliseconds ***");



return (difference < 2000)

}
"""

【问题讨论】:

    标签: karate


    【解决方案1】:

    谢谢彼得,我现在已经知道该怎么做了。

    (1) 包含功能的功能文件必须具有功能、背景和场景标签 - 即使您的文件不包含任何场景。 (*请参阅下面的示例文件)

    (2) 在您调用 FROM 的功能文件中,将以下代码添加到背景部分:

    * call read('yourfilename.feature')
    

    (3) 您现在可以使用被调用功能文件中的函数

    这是我正在调用的功能文件的结构:

    Feature: Custom Karate Methods
    This feature file contains Custom Karate Methods that can be called and used from other Feature Files
    
    Background:
    
    * def *nameofyourfunction* =
    
    #Comment describing the fuction
    
    """
    function() {
    
    *code*
    
    }
    """
    
    ****Scenario: This line is required please do not delete - or the functions cannot be called****
    

    【讨论】:

    • 很公平,对此感到抱歉。你不认为在 Stack Overflow 上花费大量时间输入答案时不投票是不礼貌的吗?
    • 好的(我以前从未使用过 Stack Overflow,所以我不知道礼仪)。我仍然认为我的功能在被调用文件的背景中更好。如果我将它移到场景部分,则在调用文件时运行该函数。我只想在需要时运行它,如果我将它留在后台,我可以这样做。
    • 和平。据我所知,应该没有区别。一个建议,看这里的第 17 行,这是一种从文件中使用 JS 函数的方法,这可能就是你所需要的:github.com/intuit/karate/blob/master/karate-demo/src/test/java/…
    • 谢谢彼得。是的,我原本打算使用 .js 文件,但在空手道中,每个 .js 文件只能有 1 个函数。您建议使用我现在已经完成的 .feature 文件。我将使用它作为主文件来包含几个可以在其他功能文件中使用的 javascript 函数——现在我知道该怎么做了。问候马特
    • 它说我明天可以接受答案。我会在星期一做。感谢您的帮助。
    【解决方案2】:

    我想你已经在这里看到了答案,而且这个问题完全是重复的:https://stackoverflow.com/a/47002604/143475(编辑:好的,也许不是)

    无论如何,我会重复我在那里发布的内容:

    • 在一个特性中定义多个函数并从多个其他特性调用它没有问题
    • 无论如何,每个函数都需要一个唯一的名称
    • 当您为该功能使用call 时,所有功能都将可用,是的,但如果您不使用它们,也没关系。如果您担心性能和内存,恕我直言,这是过早的优化
    • 如果这听起来不够好,实现您想要的一种方法是使用一堆静态方法定义一个Java 类Foo。然后你可以做Foo.myMethodOne()Foo.myMethodTwo(),让你心满意足。在您的情况下,我强烈推荐这种方法,因为您似乎期待实用方法的爆炸式增长,并且根据我的经验,在 Java 中可以更好地管理,只是因为您可以更好地维护该代码、IDE 支持、单元测试、调试和所有

    希望这是有道理的!

    【讨论】:

    • 看来我误解了这个问题。无论如何,这可能对其他人有用,所以我将其留在这里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2011-09-22
    相关资源
    最近更新 更多