Setting up MockBackend with Ionic 2


#1

I’m on RC4, and currently use the testing starter app clicker by lathonez for unit and e2e testing. I’m trying to use Mock Backend for some of my HTTP calls, but I’m having trouble adapting from Angular 2 conventions.

This tutorial here explains MockBackend with Angular 2, making an Ionic 2 app with no server. https://www.sitepoint.com/angular-2-mockbackend/

Going through it but there’s some syntax that just doesn’t fit Ionic 2. Was wondering if anyone has this set up for their service mocks in their app.


#2

Hi @heykamok,

It’s really not too hard to set up a functional, local server as your backend. I use NodeJS with Express. The Express tutorials provide good examples for HTTP GETs and RESPONSEs.

https://expressjs.com/en/starter/hello-world.html

Good luck,
Ryan


#3

Hi @ryanlogsdon, just curious to see if anyone has done it yet. Currently in my test.ts I have a bunch of { provide: SomeDataService, useClass: SomeDataMock}.

I’m assuming that once I get the MockBackend figured out, the SomeDataMock will be using MockBackend, while the SomeDataService will be using a real server(which is under construction) Currently, I just make http calls to a local json file which gives me some mock data.

This is all so I can test in depth and forge errors in HTTP responses. Thanks.


#4

Ah. Well if you’re interested in trying out the Express route, this is the JSON function I always drop in as my initial test that it’s up and running…

var quotes = [
    { author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm possible'!"},
    { author : 'Walt Disney', text : "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you"},
    { author : 'Unknown', text : "Even the greatest was once a beginner. Don't be afraid to take that first step."},
    { author : 'Neale Donald Walsch', text : "You are afraid to die, and you're afraid to live. What a way to exist."}
];

app.get('/quote/:id', function(req, res) {
    if(quotes.length <= req.params.id || req.params.id < 0) {
        res.statusCode = 404;
        return res.send('Error 404: No quote found');
    }

    var q = quotes[req.params.id];
    res.json(q);
});

To call, make an HTTP request to localhost:###/quote/#