Reputation: 3112
I am new to testing in AngularJS and just started to use testing using Karma and jasmine for a particular use case. Actually, I am a front end developer and the backend API's keep changing as the system is under migration. So I wanted to implement a test on service wherein I can catch response from the actual API and test the response where I have the same data all the time as the database is exported and is in the consistent state. Is there a way to do it? Because all articles I have read they mock the response of the API and then test the individual methods written. Or do I have to use protractor for E2E testing?
Upvotes: 2
Views: 1249
Reputation: 636
When you run tests with karma, your backend will be mocked as soon as you load angular-mocks.js (see https://docs.angularjs.org/api/ngMock/service/$httpBackend). This is what we want because we need unit tests to run quickly without having to run a backend and database.
If you need to test the interaction between your app and the real API, you need to do E2E tests with protactor, as in this kind of test, the backend is running.
Now, if you need to test the real API output, it is - in my humble opinion - the work of the backend developer. Having that said, you can of course test it yourself, but it has nothing to do with AngularJS. I'm not a NodeJS developer but there are tools to test API endpoint. You can look at SuperTest for example wich
provide a high-level abstraction for testing HTTP
Here is an example from their documentation :
var request = require('supertest');
var express = require('express');
var app = express();
app.get('/user', function(req, res) {
res.status(200).json({ name: 'tobi' });
});
request(app)
.get('/user')
.expect('Content-Type', /json/)
.expect('Content-Length', '15')
.expect(200)
.end(function(err, res) {
if (err) throw err;
});
Upvotes: 3
Reputation: 6620
Many people forget that Karma is not specific to Angular. It is made to run tests on JavaScript code, regardless of the framework you may or may not use. So, you can run tests with Karma that do not use Angular or Angular Mocks and that interact with a database. These types of tests are called integration or functional tests (there's a fine line that separates the two, depending upon how you look at it) and they should be included in every project. I have seen tests of this nature use Jasmine, and I have seen them use Mocha. The choice is yours. Either way, don't expect them to run as fast as unit tests since you'll be contending with network and database latency. When you run these tests in your development cycle is up to you. Since they take longer, most times they are only run on a full build or after the API/database have changed.
All of this being said, the developers that produce the API should be the ones writing/running these tests and providing you (the customer) with updated documentation.
Upvotes: 1