0

我有一个 fetch api 的包装方法,它返回一个承诺。看,下面的代码示例:

const fetchWrapper = (url , opts) => {
  const fetchPromise = fetch(url, opts);
  const wrapper = new Promise((resolve, reject) => {
    fetchPromise
      .then((response) => {
        if (response.status === 400 && response.headers.get('Content-Type') === 'application/json') {
          response.json()
            .then((data) => {
              if (!data.success) {
                resolve(new Promise(() => {}));
              } else {
                resolve(response);
              }
            })
            .catch(() => resolve(response));
        } else {
          resolve(response);
        }
      },
      reject);
  });
return wrapper;

所以,现在我有一个方法,我调用这个 fetchWrapper 方法,如下所示:

 async loadData() {
    const response = await fetchWrapper('/sample-template.json');
    const json = await response.json();
    this.reportTypes = json.templates;
  }

这里的问题是,我想对这个方法 loadData 进行单元测试。所以,我正在尝试使用下面的单元测试代码来存根内部方法。

const MOCK_JSON = {
    templates: [{"id": 1,"name": "Sample report 1"}, {"id": 2,"name": "Sample report 2"}]
};

const jsonOk = (body) => {
    const mockResponse = new window.Response(JSON.stringify(body), {
      status: 200,
      headers: {
        'Content-type': 'application/json',
      },
    });
    return Promise.resolve(mockResponse);
  };

describe('load data api', async () => {
    let stub;
    beforeEach(() => {
        stub = sinon.stub(fetchWrapper);
        stub.onCall(0).returns(jsonOk(MOCK_JSON));
        console.log(stub.calledOnce);
    });
    afterEach(() => { 
        stub.restore();
    });
 
   it('load all report types', async () => {
     const res = loadData();
   });
});

请让我知道进行单元测试的解决方案是什么。我尝试了多种方法,但没有找到任何可行的解决方案。帮助。

4

0 回答 0