当在Jest中抛出错误时,测试用例失败

2lpgd968  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(134)

我想测试以下函数的失败场景

homepageHandler: async function (req, res) {
    console.log(`index page. Req ${req}`);
    return JSON.stringify({
      "message": "welcome"
    });
  }

我是mocking的函数,想要throwError,其中应该有一个JSON对象

describe("Endpoints are not accessible", () => {
  it("GET request for homepage should return non-200 if error", async () => {
    const baseURL = process.env.EXPRESS_SERVER_TEST 
    console.log(`base url is ${baseURL}`);
    
    const req = {};
    
    const res = {};

    const mock = jest.spyOn(indexControllerModule, 'homepageHandler');  // spy on indexControllerModule's homepageHandler 
    
    mock.mockImplementation((res,req) => {
      throw Error(JSON.stringify(
        {
          "message": "error"
        }));
      });  // replace implementation
    
    indexControllerModule.homepageHandler(req,res)
    .then((result)=>{
      console.log(`This code path shouldn't be executed. Result is ${result}`);
    })
    .catch((error)=>{
      console.log(`error in accessing homepage: ${error}`);
      expect(error).toBe(JSON.stringify({
        "message": "error"
      }));
    })
  });  
});

当我运行测试时,我得到了错误

Endpoints are not accessible › GET request for homepage should return non-200 if error                                                                                 
                                                                                                                                                                           
    {"message":"error"}

      43 |
      44 |     mock.mockImplementation((res,req) => {
    > 45 |       throw Error(JSON.stringify(
         |             ^
      46 |         {
      47 |           "message": "error"
      48 |         }))});  // replace implementation

      at Object.Error (test/index.test.js:45:13)
      at Object.homepageHandler (test/index.test.js:50:27)

但我不知道是什么错误。我做错了什么?

kknvjkwl

kknvjkwl1#

它不起作用,因为homepageHandler是异步函数。你得这样嘲笑它:

mock.mockRejectedValue(new Error());

或更详细:

mock.mockImplementation(() => {
   return new Promise(() => { throw new Error() })
});

相关问题