Output jasmine test results to the console - javascript

I am using Jasmine (BDD Testing Framework for JavaScript) in my firefox add-on to test the functionality of my code.
The problem is that jasmine is outputing the test results to an HTML file,what I need is to Firebug Console or other solution to output the results.

Have you tried the ConsoleReporter?
jasmine.getEnv().addReporter(new jasmine.ConsoleReporter(console.log));
According to the code Jasmine has the ConsoleReporter class that executes a print function (in this case console.log) that should do what you need.
If all else fails you could just use this as a starting point to implement your own console.log reporter.
UPDATE
In newer versions of jasmine, ConsoleReporter was removed. You can either use the built-in jsApiReporter, or write your own (console) reporter, as shown in the following link: https://jasmine.github.io/tutorials/custom_reporter

In newest version of Jasmine (2.0) if you want to get test output to console you need to add following lines.
var ConsoleReporter = jasmineRequire.ConsoleReporter();
var options = {
timer: new jasmine.Timer,
print: function () {
console.log.apply(console,arguments)
}};
consoleReporter = new ConsoleReporter(options); // initialize ConsoleReporter
jasmine.getEnv().addReporter(consoleReporter); //add reporter to execution environment
Output to html is included by default however so if you don't want html output at all you have to edit your boot.js file and remove relevant lines from there. If you want to customize how output is displayed in console edit file console.js.
Source

jasmineRequire.ConsoleReporter did not exist in 2.3.0 so I used the following code:
//create a console.log reporter
var MyReporter = function(){jasmineRequire.JsApiReporter.apply(this,arguments);};
MyReporter.prototype = jasmineRequire.JsApiReporter.prototype;
MyReporter.prototype.constructor = MyReporter;
MyReporter.prototype.specDone=function(o){
o=o||{};
if(o.status!=="passed"){
console.warn("Failed:" + o.fullName + o.failedExpectations[0].message);
}
};
var env = jasmine.getEnv();
env.addReporter(new MyReporter());

For the sake of completeness here's the full configuration:
First of all run the npm install command:
npm install jasmine-console-reporter --save-dev
Then check your Jasmine configuration to make sure you got the helpers setting there:
spec/support/jasmine.json
{
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.js"
],
"helpers": [
"helpers/**/*.js"
],
"stopSpecOnExpectationFailure": false,
"random": false
}
Since helpers are executed before specs the only thing you have to do is to create a console reporter helper.
spec/helpers/reporter/consoleReporter.js
const JasmineConsoleReporter = require('jasmine-console-reporter');
let consoleReporter = new JasmineConsoleReporter({
colors: 1, // (0|false)|(1|true)|2
cleanStack: 1, // (0|false)|(1|true)|2|3
verbosity: 4, // (0|false)|1|2|(3|true)|4
listStyle: 'indent', // "flat"|"indent"
activity: false
});
jasmine.getEnv().addReporter(consoleReporter);
jasmine-console-reporter on npmjs.com
Jasmine custom reporter docs
Jasmine configuration reference

Related

How do I correctly configure mocha tests with ts_transformer_keys?

I can't seem to set the custom transformer for ts-transform-keys with my mocha tests.
I’m using mocha 6.1.4
ts-node 8.3.0 https://www.npmjs.com/package/ts-node
ts-trasnformer-keys 0.3.5 https://github.com/kimamula/ts-transformer-keys
ttypescript 1.5.7 https://github.com/cevek/ttypescript
The ts-node documentation says that you cannot set a custom transformer on the CLI, only programatically. So I'm trying to use ttypescript to get around that restriction.
I've tried the following...
Note: test.ts contains the following
import { keys } from 'ts-transformer-keys';
describe("xyz"), () => {
it("123", (done) => {
keys<CustomInterface>();
});
});
Attempt 1) - Set the ts-node with an environment variable
TS_NODE_COMPILER="ttypescript" mocha test/test.ts --require ts-node/register
Then I have the following in test/tsconfig.json
{
"compilerOptions": {
"plugins": [
{ "transform": "ts-transformer-keys/transformer" }
]
}
}
This results in Uncaught TypeError: ts_transformer_keys_1.keys is not a function which indicates that the custom transformer wasn't used at compile time.
Attempt 2) Following the typescript API example from ts-transformer-keys
I added a mocha.opts file with the following
--file test/transformer-config.js
and a transformer-config.js file with the following
const ts = require('typescript');
const keysTransformer = require('ts-transformer-keys/transformer').default;
const program = ts.createProgram(['test/test.ts'], {
strict: true,
noEmitOnError: true,
target: ts.ScriptTarget.ES5
});
const transformers = {
before: [keysTransformer(program)],
after: []
};
const { emitSkipped, diagnostics } = program.emit(undefined, undefined, undefined, false, transformers);
if (emitSkipped) {
throw new Error(diagnostics.map(diagnostic => diagnostic.messageText).join('\n'));
}
Then I invoke it like this mocha test/test.ts --require ts-node/register
This results in the following error
/Users/jjohnson/Documents/OCS/hmp/git/hmp-server/server/test/ttypescript-register.js:17
throw new Error(diagnostics.map(diagnostic => diagnostic.messageText).join('\n'));
^
Error: [object Object]
[object Object]
[object Object]
at Object.<anonymous> (/Users/jjohnson/Documents/OCS/hmp/git/hmp-server/server/test/ttypescript-register.js:17:9)
at Module._compile (internal/modules/cjs/loader.js:777:30)
...
It feels like in Attempt 1 it wasn't ever calling the code that sets the custom transformer in tsconfig.json or if it was getting called the code was failing silently.
It feels like in Attempt 2 I'm creating a new instance of the typescript program and then that fails for some reason. And even if it succeeded I'm not sure that this is the right way to go about configuring things since the ts.createProgram wants a list of RootNames for the files it will transpile.
Maybe my entire approach is wrong.
All I really want is a way that in my mocha tests I can verify that the expected result type is what the method returned. And I'd like to be able to do this w/out touching too much of the source code.
you should be able to define your required module (see below) and run ts-node programmatically. In this way, you can safely use any customer transformer.
// tsnode.js
const transformer = require('ts-transformer-keys/transformer').default;
require("ts-node").register({
transformers: program => ({
before: [
transformer(program)
]
})
});
then you can run mocha with require
mocha --require './tsnode.js' --watch-extensions ts,tsx "test/**/*.{ts,tsx}
You can tell ts-node which compiler to use in tsconfig.json. This is covered in the ts-node docs. If your using transformers presumably your also using ttypescript compiler. You just need to add this:
"ts-node": {
"compiler": "ttypescript"
}

On using jasmine reporter, I get "No spec found"

I am using jasmine-node framework for my API automation. I am able to run REST services and able to get the result using node-fetch or http. Without reporter when I run with the below command I was able to get the results in console
jasmine spec/xxx.spec.js
After that I added a reporter(pretty html reporter) for reporting. Now when I run those commands, I get the below error.
No specs found
Below is my code for reporter.js
var Jasmine = require('jasmine');
var HtmlReporter = require('jasmine-pretty-html-reporter').Reporter;
var path=require('path');
var jasmine = new Jasmine();
jasmine.loadConfigFile('./spec/support/jasmine.json');
// options object
jasmine.addReporter(new HtmlReporter({
path: path.join('./spec/helpers','results')
}));
jasmine.execute();
Below is my code for jasmine.json
{
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.js"
],
"helpers": [
"helpers/**/*.js"
],
"stopSpecOnExpectationFailure": false,
"random": true
}
Please help me with this. Also please let me know if there is any better reporter than this.Thanks in advance

Testing internal functions in Mocha ESlint error

I'm currently developing an Nodejs application and carrying out some unit tests (I'm using Mocha, Chai and Sinon).
I ran into a little ESlint error when I exported and tested an internal function.
function _buildPayload(){
//....
}
module.exports = { _buildPayload };
Then in my test script
const {_buildPayload} = requires('./someModule')
describe('Test',function(){
it('Should work',function(){
let expected = _buildPayload();
})
})
When I write the let expected = _buildPayload(); ESlint returns the following error:
error Shouldn't be accessing private attribute '_buildPayLoad'
My question is should I change the name of my function to not represent and internal even though it is?
#philipisapain makes a good point that testing internal methods may not be necessary. If you do need to do it, you have a couple options:
Disable the rule by placing /* eslint-disable rule-name */ at the top of any test scripts that call private methods.
Disable the rule in all test scripts using a glob config in your .eslintrc, provided you're using at least ESLint v4.1.0:
"overrides": [{
"files": ["*.test.js"],
"rules": [{
"rule-name": "off"
}]
}]

I am finding trouble using log4js-protractor-appender

My log4js.js file code
'use strict';
var log4js = require('log4js');
var log4jsGen = {
getLogger: function getLogger() {
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('./ApplicationLogs.log'), 'logs');
var logger = log4js.getLogger('logs');
return logger;
}
};
module.exports = log4jsGen;
My conf.js file(specific to appender section only)
"appenders": [{
"type": "log4js-protractor-appender",
"append": 'false',
"maxLogSize": 20480,
"backups": 3,
"category": "relative-logger"
}],
Problem:
1) IS there a way that the logs will get overwritten in each run.
2) Why log4js-protractor-appender is not working, instead log4js is working, the merit of the previous is that it resolves the promises which is passed as an argument.
Thats a great question. Yes log4js-protractor-appender is awesome. It is built specially for Protractor based environments and it places all logger command in Protractor Control flow and resolves Protractor promises before logging.
You were using it incorrectly. The appender options are not part of Protractor config options but can be integrated. The approach you have is a little old one and I have updated by blog post
These are the steps as an answer to your question-2
Step 1: Install log4js npm module
Step 2: Install log4js-protractor-appender module
Step 3: Add the logger object creation logic in protractor beforeLaunch() and assign it onto ​​browser protractor global object
'use strict';
var log4js = require('log4js');
beforeLaunch:function(){
if (fs.existsSync('./logs/ExecutionLog.log')) {
fs.unlink('./logs/ExecutionLog.log')
}
log4js.configure({
appenders: [
{ type: 'log4js-protractor-appender', category: 'protractorLog4js' },
{
type: "file",
filename: './logs/ExecutionLog.log',
category: 'protractorLog4js'
}
]
});
},
onPrepare: function() {
browser.logger = log4js.getLogger('protractorLog4js');
},
Step 4: Use logger object in your tests by accessing through browser.logger
describe('sample test', function(){
it('Sample Check', function(){
browser.get("http://www.protractortest.org/#/");
browser.logger.info("Testing Log4js");
browser.sleep(5000);
browser.logger.info('Displayed text is:', browser.getCurrentUrl());
var elm = element(by.css('.lead'))
browser.logger.info('Displayed text is:', elm.getText());
});
});
But one thing to note is - This appender is just an console appender and will not be able to write to file. The file will still contain unresolved promises
Sample Output:
[21:54:23] I/local - Starting selenium standalone server...
[21:54:23] I/launcher - Running 1 instances of WebDriver
[21:54:25] I/local - Selenium standalone server started at http://192.168.1.5:60454/wd/hub
Started
[2017-02-03 21:54:30.905] [INFO] protractorLog4js - Testing Log4js
[2017-02-03 21:54:35.991] [INFO] protractorLog4js - Displayed text is: http://www.protractortest.org/#/
[2017-02-03 21:54:36.143] [INFO] protractorLog4js - Displayed text is: Protractor is an end-to-end test framework for Angular and AngularJS applications. Protractor runs tests against your application running in a real browser, interacting with it as a user would.
.
Answer to your Question 1: How to overwrite logs each run. I added a simple logic in beforeLaunch() to delete old logs if they exist and its part of the code snippet I pasted above
I have check this issue with and followed the steps mentioned in Answer 1 and it works for me.
Earlier I was getting log output in Console only but now I am getting log in console and file also.
I corrected the file path passing and Set type: "file" in log4js configure in conf file.
Log4js in Conf file
Log appender in file
Please let me know if you face any issue again.
Thanks

protractor 3.0.0 and cucumber automated testing

I am currently using protractor, cucumber and chai/chai-as-promised for my automated tests. My current code is using protractor 1.8.0 and I would like to update it to the most recent version. The problem is that the most recent version of protractor doesn't support cucumber.
To use cucumber as your framework, protractor (http://angular.github.io/protractor/#/frameworks) points you to using protractor-cucumber-framework (https://github.com/mattfritz/protractor-cucumber-framework). I have tried integrating this with my current code and some smaller example projects with no luck at getting them working. The main error I get is:
Error: Step timed out after 5000 milliseconds at Timer.listOnTimeout
(timers.js:92:15)
I have tried changing the default timeout globally as cucumber suggests by:// features/support/env.js
var configure = function () {
this.setDefaultTimeout(60 * 1000);
};
module.exports = configure;
But I seem to be missing something with my setup.
So, does anyone know of a good example that can show me the proper setup for the new protractor/cucumber framework? If not, does anyone know of an example that shows how to change the default timeout globally?
You should add
this.setDefaultTimeout(60000);
to one of your step_def files. For example:
module.exports = function () {
this.setDefaultTimeout(60000);
this.After(function (callback) { ... }
}
Or you should add //features/support/env.js to
cucumberOpts:{require: ['//features/support/env.js']}
to array with your stepDefinition files
thx to #Ivan,
with cucumber-protractor-framework and typescript:
in protractor.conf.js
cucumberOpts: {
compiler: "ts:ts-node/register",
require: [
'./src/env.ts', //<- added
'./src/**/*.steps.ts'
]
},
in src/env.ts:
import {setDefaultTimeout} from 'cucumber';
setDefaultTimeout(9001);

Categories

Resources