Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch-mock with jasmine not triggering then

I have this constant:

export const clientData = fetch(`${process.env.SERVER_HOST}clientData.json`)
    .then(response => response.json());

Which works properly, and Now I'm working on the test of this, with Jasmine and fetch-mock

This is my test:

import { clientData } from '../../../src/js/services/client-data.fetch';
import fetchMock from 'fetch-mock';

describe('test', () => {
    const exampleResponse = {
        clientData: 'test'
    };

    beforeAll(() => {
        fetchMock.mock('*', exampleResponse);
    });

    it('ooo', () => {
        console.log('here', clientData);
        var a = clientData;
        a.then(b=> console.log(b))
    });
});

The console.log of clientData returns a Promise (Which is fine), but the then is never triggered.

Not seeing why, what is wrong with my code?

like image 673
Pablo Avatar asked Aug 05 '17 12:08

Pablo


1 Answers

This happens because the test execution is synchronous in nature and it doesn't wait for the assertion to happen, so you have to pass a done callback and call it from your test inside the then callback

Like this:

import { clientData } from '../../../src/js/services/client-data.fetch';
import fetchMock from 'fetch-mock';

describe('test', () => {
    const exampleResponse = {
        clientData: 'test'
    };

    beforeAll(() => {
        fetchMock.mock('*', exampleResponse);
    });

    it('ooo', (done) => {
        console.log('here', clientData);
        var a = clientData;
        a.then(b=> {
            console.log(b);
            done();
        })
    });
});
like image 94
Shivam Latawa Avatar answered Oct 23 '22 09:10

Shivam Latawa