I am trying to do unit testing with Mocha and Chai. The test runs successfully in terminal, but when I check the testrunner.html file in browser it is blank and just shows "passes: 0failures: 0duration: 0s"
But in terminal it shows:
$ mocha
Array
✓ should start empty
1 passing (18ms)
HTML
In this order in your HTML
Link to a mocha css stylesheet.
<link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
Write a div tag with id='mocha'. The tests will be inserted in this div, which will allow you to see them in the browser.
<div id="mocha"></div>
Write a script tag to load mocha.
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
Write a script tag to load any other dependencies like chai.
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.1.0/chai.js"></script>
Setup the mocha BDD api (or TDD depending on how you are writing your tests).
<script>mocha.setup("bdd");</script>
Write your test (inline or link to an external JavaScript file).
BDD example:
describe("addition", function() {
it("adds 1 and 1", function() {
expect(1 + 1).to.equal(2);
});
});
Run Mocha.
mocha.run();
Snippet Example
Try running this snippet
<!-- link to mocha css stylesheet -->
<link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
<!-- write a div with id "mocha" for the output to be inserted into -->
<div id="mocha"></div>
<!-- load mocha framework -->
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<!-- load any other libraries like the chai assertion library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.1.0/chai.js"></script>
<!-- setup mocha to use the BDD interface -->
<!-- Note: you can use TDD here instead -->
<!-- depending on how you are writing your tests -->
<!-- more information: http://mochajs.org/#tdd -->
<script>
mocha.setup("bdd");
</script>
<!-- write tests -->
<script>
// access 'expect' from chai
var expect = chai.expect;
// write tests (BDD example)
describe("addition", function() {
it("adds 1 and 1", function() {
expect(1 + 1).to.equal(2);
});
it("adds 1000 and 10", function() {
expect(1000 + 10).to.equal(1010);
});
});
describe("subtraction", function() {
it("subtracts 1 from 1", function() {
expect(1 - 1).to.equal(0);
});
it("subtracts 10 from 1000", function() {
expect(1000 - 10).to.equal(990);
});
});
describe("multiplication", function() {
it("multiplies 1 by 1", function() {
expect(1 * 1).to.equal(1);
});
it("multiplies 1000 by 10", function() {
expect(1000 * 10).to.equal(10000);
});
});
describe("division", function() {
it("divides 1 by 1", function() {
expect(1 / 1).to.equal(1);
});
it("divides 1000 by 10", function() {
expect(1000 / 10).to.equal(100);
});
});
</script>
<!-- run mocha -->
<script>
mocha.run();
</script>
Demo
Here is a CodePen Demo that does not use so much inline JavaScript.
Documentation
Useful information can be found here at the official documentation.
Related
I'm trying to write tests for our Angular 2 app with Jasmine. Followed a few tutorials, tried a lot. It works with basic tests, but once I make an instance of a component or try to mock it I just get no testresults. According to Angular Doc it's 'That's Jasmine saying "things are so bad that I'm not running any tests."'
Strangely enough, BlobViewModel does work. Whenever I comment or delete the 'this.const = new Constants();' it works again. Tried with multiple classes, always get the same results.. No logs/errors in chrome.
We're using Angular RC4 with Jasmine 2.4.1.
This is my .spec file:
import {Component, OnInit, OnDestroy } from "#angular/core";
import {Router} from '#angular/router';
import { Constants } from './shared/app.constants';
describe('component test', () => {
beforeEach(function () {
this.const = new Constants(); // THIS BREAKS IT
});
it('Tests', () => {
//Tests come here
//this.const.Signalr();
});
});
describe('1st tests', () => {
it('true is true', () => expect(true).toEqual(true));});
describe('BlobViewModel', () => {
var id = 1;
var localhost = "http//localhost";
var fullpath = "http//fullpathtoapplication.com";
var printername = "Printy print";
var papersize = "A4";
var blobmodel = new BlobViewModel(id, localhost, fullpath, printername, papersize);
it('BlobviewModel aanmaken', () => {
expect(blobmodel.ID).toEqual(id);
expect(blobmodel.FullLocalUrl).toEqual(localhost);
expect(blobmodel.FullPath).toEqual(fullpath);
expect(blobmodel.PrinterName).toEqual(printername);
expect(blobmodel.PaperSize).toEqual(papersize);
});
});
HTML file for the .spec runner:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Ng App Unit Tests</title>
<link rel="stylesheet" href="../js/jasmine-core/lib/jasmine-core/jasmine.css">
<script src="../js/jasmine-core/lib/jasmine-core/jasmine.js"></script>
<script src="../js/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
<script src="../js/jasmine-core/lib/jasmine-core/boot.js"></script>
</head>
<body>
<!-- #1. add the system.js library -->
<script src="../js/systemjs/dist/system.src.js"></script>
<script src="../app/Systemjs.config.js"></script>
<script>
// #2. Configure systemjs to use the .js extension
// for imports from the app folder
System.config({
packages: {
'../app': { defaultExtension: 'js' }
}
});
// #3. Import the spec file explicitly
System.import('../app/file.spec.js')
// #4. wait for all imports to load ...
// then re-execute `window.onload` which
// triggers the Jasmine test-runner start
// or explain what went wrong.
.then(window.onload)
.catch(console.error.bind(console));
</script>
</body>
</html>
In the end I figured it out, had to import the "Reflect-metadata" package in the html file:
<script src="../js/reflect-metadata/Reflect.js"></script>
I have a simple test I'm trying to run through jasmine. Here are the ts files.
Unit-Test.html
<html>
<head>
<title>1st Jasmine Tests</title>
<link rel="stylesheet" href="../node_modules/jasmine-core/lib/jasmine-core/jasmine.css" />
<script src="../node_modules/systemjs/dist/system.src.js"></script>
<script src="../node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="../node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
<script src="../node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
<script src="../node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>
<!--<script src="../node_modules/zone/lib/zone.js"></script>-->
</head>
<body>
<script>
// #2. Configure systemjs to use the .js extension
// for imports from the app folder
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
packages: {
'test': { defaultExtension: 'js' },
'app': { defaultExtension: 'js' }
}
});
// #3. Import the spec file explicitly
System.import('test/test.spec')
// #4. wait for all imports to load ...
// then re-execute `window.onload` which
// triggers the Jasmine test-runner start
// or explain what went wrong
.then(window.onload)
.catch(console.error.bind(console));
</script>
</body>
</html>
test.spec.ts
import {TestComponent} from "../app/components/about/test.component"
describe('Test Component->', () => {
it('has name given in the constructor', () => {
var t1 = new TestComponent('Super Cat');
expect(t1.myValue).toEqual('Super Cat');
});
it('does not have the id given in the constructor', () => {
var t2 = new TestComponent('Super Cat');
expect(t2.myValue).not.toEqual(1);
});
});
test.component.ts NOTICE THE COMMENTED OUT COMPONENT ANNOTATION
import {Component} from 'angular2/core';
//#Component({
// selector: 'test-component',
// templateUrl: "<div></div>",
//})
export class TestComponent {
constructor(value: string) {
this.myValue = value;
}
public myValue = '';
onKey2() {
return this.myValue;
}
}
Now if I hit the unit-test.html with the #Copmonent annotation commented out I get the following result
however if I uncomment the #Component annotation line, as this is really how my components will be defined... I get the following error
Can someone please tell me why I'm getting this error. I've tried importing "reflect-metadata" as well with no success
Ok, I think I got it... I had to change the script section in my unit-test.html to the following in this exact order!! Now I just have to figure out how to pull this into a separate project
<script src="../node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="../node_modules/systemjs/dist/system.src.js"></script>
<script src="../node_modules/rxjs/bundles/Rx.js"></script>
<script src="../node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="../node_modules/angular2/bundles/testing.dev.js"></script>
<script src="../node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
<script src="../node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
<script src="../node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>
I prefer unit testing in the browser because I enjoy the legible formatting of testing frameworks like mocha.
Is there an easy way run add-on sdk unit tests in the browser?
Edit: I'm not looking to do regression testing. With mocha, for example, I can create an HTML page like this:
<head>
<title>Tests</title>
<link rel="stylesheet" href="mocha.css" />
</head>
<body>
<script src="mocha.js"></script>
<script src="chai.js"></script>
<script src="main-content.js"></script>
<script>mocha.setup('bdd')</script>
<script src="main-content-test.js"></script>
<script>
mocha.run();
</script>
</body>
The output looks like the picture I linked to above. This is what I mean by unit testing in the browser.
Edit 2: I'm trying to unit test my modules (using require("sdk/test"), not my content scripts.
There is not a prebuilt way to do this, it would require a little jerry-rigging.
All that you need in addition to your page is a page-mod like this:
require('sdk/page-mod').PageMod({
include: require('sdk/self').data.url('testpage.html'),
contentScript: 'unsafeWindow.addon={on: self.port.on, emit: self.port.emit}',
contentScriptWhen: 'start',
onAttach: function(worker) {
worker.port.on('test-1', function() {
worker.port.emit('test-1', {})
});
// ...
}
});
which would listen for test events, perform the test, and emit the results back. Then your test page test code would listen for the test results like so:
function test() {
addon.on('test-1', function(results) {
// loop through results and pass/fail
});
addon.emit('test-1');
}
I have some JavaScript that I'm testing with Jasmine. I want to run the tests in the browser window when a user presses "run tests". With Jasmine 1.3, I have successfully set that up as shown in this JSFiddle with this code:
run tests
<script type="text/javascript">
window.jasmineEnv = (function () {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
return jasmineEnv;
})();
</script>
Jasmine 2.0 offers some new capabilities that I really need. However, I cannot figure out how to get it setup such that the tests run when someone clicks a "run tests" button. I'm using the new boot.js file. However, I'm not having any luck. Can someone please help me migrate that sample from Jasmine 1.3 to Jasmine 2.0?
Thank you
Test cases execution is triggered by below snipped in file boot.js:
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
htmlReporter.initialize();
env.execute();
};
Either you can modify this implementation in boot.js file itself to execute under a function call or you can write your custom boot code inspired from actual boot.js.
Can't post this as a comment yet!
Jasmine 2.0 in jsfiddle http://jsfiddle.net/88Xa6/4/ As mentioned by #user3037143 initialization is handled at boot.js.
Ensure the library files are in place:
<script type='text/javascript' src="/libs/jasmine/2.0.0/jasmine.js"></script>
<script type='text/javascript' src="/libs/jasmine/2.0.0/jasmine-html.js"></script>
<link rel="stylesheet" type="text/css" href="/libs/jasmine/2.0.0/jasmine.css">
<!-- Add any custom reporters (Console / Junit / etc) here.
Ensure necessary initialization triggers are set in
boot when adding more reporters. -->
<script type='text/javascript' src="/libs/jasmine/2.0.0/boot.js"></script>
You can either choose to include the spec or have them defined inline:
<script src="spec.js"></script>
or
<script type='text/javascript'>
describe("My Suite", function() {
it("Should be true", function() {
expect(1).toBe(1);
});
});
</script>
I want to test my angular app with Yeoman which use Mocha with Phantom and Chai for assertion.
But when i run any sample test case the test case do not run properly it shows PhantomJs timed out due to missing Mocha run() call.Non angular Cases are working fine in test case.
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Mocha Spec Runner</title>
<link rel="stylesheet" href="lib/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script src="lib/mocha/mocha.js"></script>
<script>mocha.setup('bdd')</script>
<script src="lib/chai.js"></script>
<script>
expect = chai.expect;
assert = chai.assert;
</script>
<script>
function addSum(num1, num2) {
return num1 + num2;
}
</script>
<script>
(function() {
describe('Give it some context', function() {
it('should simulate promise', inject(function ($q, $rootScope) {
assert.notStrictEqual(3, '3', 'no coercion for strict equality');
/* var deferred = $q.defer();
var promise = deferred.promise;
var resolvedValue;
promise.then(function(value) { resolvedValue = value; });
expect(resolvedValue).to.be.undefined;
// Simulate resolving of promise
deferred.resolve(123);
// Note that the 'then' function does not get called synchronously.
// This is because we want the promise API to always be async, whether or not
// it got called synchronously or asynchronously.
expect(resolvedValue).to.be.undefined
// Propagate promise resolution to 'then' functions using $apply().
$rootScope.$apply();
expect(resolvedValue).to.equal(123);*/
}));
});
})();
</script>
<!-- trigger the mocha runner -->
<script src="runner/mocha.js"></script>
</body>
</html>
Have you tried using protractor? It has been developed specifically for testing end to end angularjs apps (by the angularjs team). https://github.com/angular/protractor
It has it's own runner, which you install with:
npm install protractor -g
and then the runner is executed with:
protractor /configfile.cfg
No need for an HTML page to run the tests.
The config file is quite simple (you can see the options in the source code).
With that, you'll have the spec defined as:
// myTest.js
describe('angularjs homepage', function() {
it('should greet the named user', function() {
browser.get('http://www.angularjs.org');
element(by.model('yourName')).sendKeys('Julie');
var greeting = element(by.binding('yourName'));
expect(greeting.getText()).toEqual('Hello Julie!');
});
});