I would like to Jasmine test that Welcome.go has been called. Welcome is an angular service.
angular.module('welcome',[])
.run(function(Welcome) {
Welcome.go();
});
This is my test so far:
describe('module: welcome', function () {
beforeEach(module('welcome'));
var Welcome;
beforeEach(inject(function(_Welcome_) {
Welcome = _Welcome_;
spyOn(Welcome, 'go');
}));
it('should call Welcome.go', function() {
expect(Welcome.go).toHaveBeenCalled();
});
});
Note:
Testing in AngularJS is achieved by using the karma framework, a framework which has been developed by Google itself. The karma framework is installed using the node package manager. The key modules which are required to be installed for basic testing are karma, karma-chrome-launcher ,karma-jasmine, and karma-cli.
Jasmine is a behavior development testing framework. Unit tests are written using Jasmine and are run to see if individual parts of an application are working correctly. As a result, unit tests will either pass or fail depending on if the code is working correctly or has a bug.
Similar to Karma, it’s also the recommended testing framework within the Angular documentation as it’s setup for you with the Angular CLI. Jasmine is also dependency free and doesn’t require a DOM. As far as features go, I love that Jasmine has almost everything I need for testing built into it.
An environment to run angular tests is being created using all the imports at the beginning of the file. TestBed is a powerful unit testing tool provided by angular, and it is initialized in this file. Finally, karma loads all the test files of the application matching their names against a regular expression.
Jasmine is the framework we are going to use to create our tests. It has a bunch of functionalities to allow us the write different kinds of tests. karma. Karma is a task runner for our tests. It uses a configuration file in order to set the startup file, the reporters, the testing framework, the browser among other things.
Before running any test in angular you need to configure an angular testbed. This allows you to create an angular environment for the component being tested. Any module, component or service that your tested component needs have to be included in the testbed. Finally, after setting the configuration, you call the compile components function.
Managed to figure it out. Here is what I came up with:
'use strict';
describe('module: welcome', function () {
var Welcome;
beforeEach(function() {
module('welcome', function($provide) {
$provide.value('Welcome', {
go: jasmine.createSpy('go')
});
});
inject(function (_Welcome_) {
Welcome = _Welcome_;
})
});
it('should call Welcome.go on module run', function() {
expect(Welcome.go).toHaveBeenCalled();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With