Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何使用CodeceptJS对JS函数进行单元测试_Unit Testing_Codeceptjs - Fatal编程技术网

Unit testing 如何使用CodeceptJS对JS函数进行单元测试

Unit testing 如何使用CodeceptJS对JS函数进行单元测试,unit-testing,codeceptjs,Unit Testing,Codeceptjs,我已经为一个项目设置了CodeceptJS,并使用它来测试各种端到端场景 现在,我想将测试套件扩展到并运行单元测试,以验证自定义JS函数的功能 例如:我有一个全局对象App,它具有version属性。作为第一个测试,我想确认App.version是否存在并具有值 我的第一次尝试是一个test.js文件,其中包含以下代码: Feature('Unit Tests'); Scenario('Test App presence', ({ I }) => { I.amOnPage('/'

我已经为一个项目设置了CodeceptJS,并使用它来测试各种端到端场景

现在,我想将测试套件扩展到并运行单元测试,以验证自定义JS函数的功能

例如:我有一个全局对象
App
,它具有
version
属性。作为第一个测试,我想确认
App.version
是否存在并具有值

我的第一次尝试是一个test.js文件,其中包含以下代码:

Feature('Unit Tests');

Scenario('Test App presence', ({ I }) => {
    I.amOnPage('/');

    I.executeScript(function() {return App.version})
        .then(function(value) { I.say(value) } );
});
此代码存在问题

  • 主要问题:我如何断言
    App.version
    存在?
    我的脚本可以显示该值,但如果缺少该值,则不会失败
  • 对于这样一个简单的测试,我的代码非常复杂。
    我确信有一种更干净/更快的方法来执行该测试,对吗

  • 以下是一个适合我的解决方案:

    从浏览器读取数据:
  • 我通过
    npx codeept gh
    创建了一个自定义助手,并将其命名为
    BrowserAccess
  • 助手函数
    getBrowserData
    使用
    this.helpers['puppeter'].page.evaluate()
    从浏览器作用域运行并返回自定义代码。文件
  • 自定义断言:
  • 安装该软件包,例如
    npm i codeceptjs assert
  • AssertWrapper
    -helper添加到codecept配置文件中。这将启用类似于
    I.assert(a,b)

  • 完整代码 codecept.conf.js

    exports.config = {
        helpers: {
            AssertWrapper: {
                require: "codeceptjs-assert"
            },
            BrowserAccess: {
                require: './browseraccess_helper.js'
            },
            ...
        },
        ...
    }
    
    browseraccess\u helper.js

    exports.config = {
        helpers: {
            AssertWrapper: {
                require: "codeceptjs-assert"
            },
            BrowserAccess: {
                require: './browseraccess_helper.js'
            },
            ...
        },
        ...
    }
    
    const Helper=require('@codeceptjs/Helper');
    类BrowserAccess扩展了帮助程序{
    异步getBrowserData(symbolName){
    const currentPage=this.helpers['puppeter'].page;
    让我们重新来过;
    试一试{
    res=等待当前页面。评估((evalVar)=>{
    让我们重新来过;
    试一试{
    res=eval(evalVar);
    }捕获(e){
    }
    返回承诺。解决(res);
    },符号名称);
    }捕捉(错误){
    res=null;
    }
    返回res;
    }
    }
    
    jsapp_test.js(测试现在是
    async

    特性(“单元测试”);
    场景('testapppresence',async({I})=>{
    I.amOnPage('/');
    const version=await I.getBrowserData('App.version');
    I.assertOk(版本);
    });