Grunt代码覆盖率不起作用

时间:2016-07-12 20:01:04

标签: javascript node.js gruntjs mocha istanbul

我有以下运行mocha测试的grunt文件OK(运行grunt.js后我得到了测试结果)现在我想添加一个代码并使用https://github.com/taichi/grunt-istanbul模块。但当我运行grunt.js什么都没发生时,有什么想法吗?

我想要的只是在mocha测试运行之后,它将运行代码覆盖率和一些报告?任何新的代码覆盖都会很棒

这是我的项目结构

protected String doInBackground(String... params)
    {
     String call_type=params[0];
        if(call_type.equals("login"))
        {
            try {
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)     url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream OS = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String email,pass;
                email=params[1];
                pass=params[2];

                String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
                        URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(pass, "UTF-8");

                bufferedWriter.write(data);


                InputStream IS = httpURLConnection.getInputStream();
                BufferedReader BR= new BufferedReader(new InputStreamReader(IS));
                StringBuilder stringBuilder = new StringBuilder();
                String line="";
                while ((line=BR.readLine())!=null)
                {
                    stringBuilder.append(line+"\n");
                }
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                //IS.close();
                httpURLConnection.disconnect();
                Thread.sleep(500);
                Log.d("Test","Test 3 pass");
                return  stringBuilder.toString().trim();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
**strong text**/*my onPostExecute method is as below;*/***

 @Override 
    protected void onPostExecute(String json)
    {

        try
        {
            progressDialog.dismiss();

            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArray=jsonObject.getJSONArray("server_response");
            *******//here exception coming org.json.JSONException: Value [{"code":"login_true","name":"hhh","email":"hhh"}] of type org.json.JSONArray cannot be converted to JSONObject and compiler jumps to the exception part*******
            JSONObject JO= jsonArray.getJSONObject(0);
            String code=JO.getString("code");
            String message=JO.getString("message");

            if(code.equals("reg_true"))
            {
                ShowDialog("Registration Success",message,code);
            }
            else if (code.equals("reg_false"))
            {
                ShowDialog("Registration Fail",message,code);
            }
            else if(code.equals("login_true"))
            {
                Intent intent= new Intent(activity,HomeActivity.class);
                intent.putExtra("message",message);
                activity.startActivity(intent);
            }
            else if(code.equals("login_false"))
            {
                ShowDialog("Login Error,",message,code);
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
**/* php scrip is as follows: (login.php)*/**
<?php
    require"init.php";

$email=$_POST["email"];
$pass=$_POST["pass"];

$sql_query="select name, email from beneficiary_details where email like '".$email."' and pass like '".$pass."' ";
$result=mysqli_query($con,$sql_query);
$response = array();

 $rowcount=mysqli_num_rows($result);
//print_r( $rowcount);
    if($rowcount > 0)
    {

        $row=mysqli_fetch_row($result);
        $name=$row[0];
        $email=$row[1];
        $code="login_true";

        array_push($response,array("code"=>$code,"name"=>$name,"email"=>$email));
        echo json_encode($response);
    }
    else
    {
        $code="login_false";
        $message="User not found, Please try again..";
        array_push($response,array("code"=>$code,"message"=>$message));
        echo json_encode($response);
    }
    mysqli_close($con);
?>
**plz find out where I am doing mistake???

这是我尝试过的咕噜声中的代码

myApp
 -server.js
 -app.js
 -test
   -test1.spec
   -test2.spec
 -test-reports
 -grunt.js
 -utils
  -file1.js
  -file2.js
 -controller
  -file1.js
  -file2.js

如果有摩卡代码覆盖率可以帮助它也很好,我希望在运行测试后我能够看到包含所有代码覆盖率的报告。

我希望对文件夹utils和控制器(那里的所有文件)的覆盖率我应该如何配置?

更新

这是我用于jasmin的东西,我想我应该改为mocha

module.exports = function (grunt) {

    var path = require('path');

    process.env.RESOURCE_PATH_PREFIX = "../";
    var d = new Date();

    var datestring = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " +
        d.getHours() + ":" + d.getMinutes();

    var npmCommand = path.dirname(process.execPath).concat('/npm');
    var reportDir = "./test-reports/" + datestring;


    grunt.initConfig({
        jasmine_nodejs: {
            // task specific (default) options
            options: {
                specNameSuffix: ["-spec.js"], 
                helperNameSuffix: "helper.js",
                useHelpers: false,
                stopOnFailure: false,
                reporters: {
                    console: {
                        colors: true,            
                    },
                    junit: {
                        savePath: "./test-reports",
                        filePrefix: "testresult",
                    }
                }
            },
            test: {
                specs: [
                    "test/*",
                ]
            },
            makeReport: {
              src: './test-reports/coverage.json',//should I create this file?or its created automatically ?
               options: {
                 type: ['lcov', 'html'],
                   dir: reportDir,
                   print: 'detail'
        }
    },
    coverage: {
        APP_DIR_FOR_CODE_COVERAGE: "./utils/*.js",//HERE IS THE PATH OF THE UTILS Folder which all the js login which I want to test there
        clean: ['build'],
        instrument: {
            files: tasks,//WHAT IS TASKS????
            options: {
                lazy: true,
                basePath: 'build/instrument/'//I DONT KNOW WHAT IT IS???
            }
        },
        reloadTasks: {
            rootPath: 'build/instrument/tasks'//SHOULD I USE IT????
        },
        storeCoverage: {
            options: {
                dir: reportDir
            }
        }
    }
    });


    grunt.loadNpmTasks('grunt-jasmine-nodejs');
    grunt.loadNpmTasks('grunt-istanbul');
    grunt.registerTask('default', ['jasmine_nodejs']);
    grunt.registerTask('cover', ['instrument', 'test',
        'storeCoverage', 'makeReport']);

};

我该如何改变它? 我的测试语法类似(jasmine / mocha),我想要的只是运行我的测试并在运行代码覆盖后

1 个答案:

答案 0 :(得分:5)

我会给你一个间接答案。我之前已经开始使用代码覆盖,但使用了不同的插件(以及mocha)。我不确定你是否愿意为jasmine换取mocha,但我会说在遇到这个问题之前我遇到了各种代码覆盖插件。我想你会同意配置既简洁又明显。

您想要的插件是grunt-mocha-istbanbul,以下是Gruntfile的示例配置:

module.exports = function(grunt) {
  grunt.initConfig({
    clean: ['coverage'],
    mocha_istanbul: {
      coverage: {
        src: 'test',
        options: {
          timeout: 20000,
          'report-formats': 'html',
          print: 'summary',
          check: {
            lines: 90,
            statements: 90,
            functions: 100,
            branches: 80
          }
        }
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-mocha-istanbul');
  grunt.registerTask('default', ['clean', 'mocha_istanbul']);
}