Vanilla mocks on Jasmine
Set up
- Mock the method
getFlag
onmyApp
.1
spyOn(myApp, "getFlag");
Mocks
Return values
Simple
1
spyOn(myApp, "getFlag").and.returnValue(true);
Fake Functions
1
2
3spyOn(myApp, "useFlagForSomething").and.callFake(function() {
return "I'm replacing the real function with this";
});
Verify code was called
Verify called
1
spyOn(myApp, "getFlag").and.callThrough();
Verify not called
1
expect(myApp.reallyImportantProcess).not.toHaveBeenCalled();
Assert on function call
1
expect(myApp.reallyImportantProcess).toHaveBeenCalledWith(123, "abc");
Async tests
Code example
1
2
3
4
5
6
7
8var flag = false;
function testAsync(done) {
// Wait two seconds, then set the flag to true
setTimeout(function () {
flag = true;
}, 2000);
}Specs
1
2
3
4
5
6
7
8
9
10describe("Testing async calls with beforeEach and passing callback", function () {
beforeEach(function (done) {
// Make an async call, passing the special done callback
testAsync(done);
});
it("Should be true if the async call has completed", function () {
expect(flag).toEqual(true);
});
});
Async-await
Code example
1
2
3
4
5
6
7function returnTrueAsync() {
return new Promise(resolve => {
setTimeout(() => {
resolve(true);
}, 1000);
});
}Specs
1
2
3
4
5
6
7
8
9
10
11
12describe("Testing async functions", () => {
it("Should work with async/await", async () => {
// Arrange
let flag = false;
// Act
flag = await returnTrueAsync();
// Assert
expect(flag).toBeTruthy();
});
});