用jasmine进行fetch-mock然后不会触发

时间:2017-08-05 12:59:25

标签: javascript unit-testing jasmine karma-jasmine jest-fetch-mock

我有这个常数:

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

哪种方法正常,现在我正在使用Jasmine和fetch-mock

进行测试

这是我的测试:

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))
    });
});

clientData的console.log返回Promise(没关系),但永远不会触发then

没看到原因,我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

发生这种情况是因为测试执行本质上是同步的,它不会等待断言发生,因此您必须传递 done 回调并从 then 内的测试中调用它回调

像这样:

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();
        })
    });
});