Skip to content

Instantly share code, notes, and snippets.

@demisx
Last active January 28, 2018 03:56
Show Gist options
  • Save demisx/10b4c90fc675014eefe3 to your computer and use it in GitHub Desktop.
Save demisx/10b4c90fc675014eefe3 to your computer and use it in GitHub Desktop.
AngularJS 1.x Unit Testing with Mocha/Chai/Chai-as-promised

Controllers

describe('ViewAdDetailController', function() {
 it('does something', function() {
 ...
 });
}

Services

States

Models

Directives

var opts = { call: function (msg) { console.log(msg); } };
var mock = sinon.mock(opts);
// You state your success criteria upfront
mock.expects("call").once().withExactArgs("Hello World");
/* ... twice, atMost, never, exactly, on, etc ... */
opts.call("Hello World");
mock.verify();
mock.restore();
// Sinon spy function
var callback = sinon.spy();
callback();
callback.called;
callback.callCount;
callback.calledWith(arg1);
callback.threw();
callback.returned(obj);
callback.calledBefore(spy);
callback.calledAfter(spy);
// Sinon spy method
sinon.spy($, "ajax");
$.ajax({ / ... / });
var call = $.ajax.getCall(0);
call.args;
call.exception;
call.returnValue;
$.ajax.restore();
var stub = sinon.stub();
var opts = { call: function (msg) { console.log(msg); } };
// We can control how the sinon.stub() will behave based on how it’s called!
stub.withArgs("Hello").returns("World");
stub.withArgs("Wuz").returns("Zup?");
stub.withArgs("Kapow").throws();
stub.withArgs(opts).yieldsTo("call", ["Howdy"]);
stub("Hello"); // "World"
stub(opts); // "Howdy"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment