带茉莉花的 fetch-mock 然后不触发

Pab*_*blo 6 javascript unit-testing jasmine karma-jasmine jest-fetch-mock

我有这个常数:

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

哪个工作正常,现在我正在用 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))
    });
});
Run Code Online (Sandbox Code Playgroud)

的 console.logclientData返回一个Promise(这很好),但then永远不会触发。

不明白为什么,我的代码有什么问题?

小智 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();
        })
    });
});
Run Code Online (Sandbox Code Playgroud)