测试失败时如何使Newman的节点脚本失败

时间:2018-10-23 06:12:01

标签: node.js jenkins newman

我有一个可以工作的纽曼脚本:

                var fs = require('fs'),
                newman = require('newman'),

                results = [];

            newman.run({
                reporters: 'cli',
                collection: require('.temp.json'),
                iterationData: './data.jsp',
                reporters: ['cli', 'html'],
                reporter: {
                    html: {
                        export: './newman/htmlResults.html', // If not specified, the file will be written to `newman/` in the current working directory.
                    }
                }
            })
            .on('request', function (err, args) {
                if (!err) {
                    // here, args.response represents the entire response object
                    var rawBody = args.response.stream, // this is a buffer
                    body = rawBody.toString(); // stringified JSON

                    results.push(JSON.parse(body)); // this is just to aggregate all responses into one object
                }
            })
            // a second argument is also passed to this handler, if more details are needed.
            .on('done', function (err, summary) {
                // write the details to any file of your choice. The format may vary depending on your use case
                fs.writeFileSync('migration-report.json', JSON.stringify(results, null, 4));
                if(summary.run.failures.length !== 0){
                    console.log("\\rThere are test failures")
                    //here I can exit but the Newman summary isn't showed
                }
            });

该脚本可以运行,但是即使有测试失败,它也可以成功完成。显示了测试失败,但我想以退出代码1之类的脚本结束脚本,因为我将在Jenkins中运行此脚本,并且我不会根据buildresult颜色检查测试是否有效。如何在节点中执行此操作?

1 个答案:

答案 0 :(得分:0)

将断言“ Chai”库添加到测试中,并使用其方法断言测试结果 阅读更多: https://www.chaijs.com/ https://www.getpostman.com/docs/v6/postman/scripts/postman_sandbox_api_reference

const chai = require('chai')
 expect = chai.expect;

并根据您要声明的内容(statusCode,reposneBody等)放入一个声明 对于实例:断言您希望您的响应主体将具有一个内部包含3个对象的数组

.on('request', function (err, args) {
                if (!err) {
                    // here, args.response represents the entire response object
                    var rawBody = args.response.stream, // this is a buffer
                    body = rawBody.toString(); // stringified JSON

                    results.push(JSON.parse(body)); // this is just to aggregate all responses into one object
                    expect(body.array.length === 3).to.equal(true)// **EXAMPLE**
                }
            })

pm.expect(res).to.have.property('code', 200);
pm.expect(res).to.have.property('status', 'OK');

根据您的请求检查响应的状态码。

阅读:https://www.getpostman.com/docs/v6/postman/scripts/postman_sandbox_api_reference