簡體   English   中英

開玩笑 - 嘗試捕捉單元測試失敗

[英]Jest - try catch unit test fails

我在使用 jest 創建單元測試時遇到問題。

exportMyData.js

const createJobTrasferSetArray = async () => {
  const data = exportData();
  const jobTransferSet = [];

  try {
    data.forEach((element) => {
      const JobPathArray = element.JobPath.split(/[,\r\n]+/)
        .filter((JobPathElement) => JobPathElement !== '');

      // Create an object
      const jobTransferSetObj = {
        coworkerID: element.CoworkerID,
        jobPath: JobPathArray,
      };
      jobTransferSet.push(jobTransferSetObj);
    });
    return jobTransferSet;
  } catch (e) {
   console.error(`Coldn't create jobTransferSet Array: ${JSON.stringify(e)}`);
return e;
  }
};

exportMyData.test.js

const exportData = require('./exportMyData');

describe('Read data from Excel and creat formated json output', () => {
//Test passed through
  it('convert read data from Excel to an array', async () => {
    mockedJobTransferSetRaw.mockReturnValue(jobTrasfarSetRaw);
    const result = await exportData.createJobTrasferSetArray();
    expect(result[0].coworkerID).toEqual(jobTransferSetArray[0].coworkerID);
    expect(result[0].jobPath).toEqual(jobTransferSetArray[0].jobPath);
    expect(result).not.toBeNull();
  });
  //Test fails
  it('Error on convert to an array', async () => {
    try {
    const result = await exportData.createJobTrasferSetArray();
    result.mockRejectedValue(new Error('something went wrong'));
    } catch (error) {
      expect(error.message).toEqual('Error: something went wrong');
    }
  });
});

我知道我的 tst 案例有問題,但我無法找出解決方案。 請幫忙!

首先,您應該盡可能避免在單元測試中使用 try/catch(作為最佳實踐)。 你總是可以使用 jest 的助手:

    await expect(class.method(param)).rejects.toThrow();
    await expect(async () => class.method(param1, param2)).rejects.toThrow(Exception);

其次,你的嘗試是空的,它怎么會捕捉到什么都沒有做?

所以這:

    try {
    } catch (error) {
      expect(error.message).toEqual('Error: something went wrong');
    }

應該變成這樣:

    try {
    // call some methods, do something...

    } catch (error) {
      expect(error.message).toEqual('Error: something went wrong');
    }

如果你想進一步 go,你甚至不需要 try/catch 部分,但我會先修復那個空的 try/catch。

如果我是正確的,這是調用一個會拋出異常的方法

    const result = await exportData.createJobTrasferSetArray();
    result.mockRejectedValue(new Error('something went wrong'));

我不完全確定您打算在那里做什么,但似乎您嘗試了 mocking 您的方法在調用后返回? 也許分享一些它的邏輯,以便我們可以更好地幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM