简体   繁体   中英

How do I test (jest) to expect return?

Using Jest how do I test for return

For example using Lambda:

exports.handler = async (event, context, callback) => {
  try {
    const orders = await getOrders();

    if (!orders) {
      console.log("There is no Orders");
      return; //<< How do test this?
    }

    // Something else
  } catch (err) {
    throw new;
  }
};

I am able to test the console log but I also like to test to expect return as well

Currently I am using this in the test:

  it("should terminate if there is no order", async () => {
    console.log = jest.fn();

    let order = await func.handler();
     expect(console.log.mock.calls[0][0]).toBe('There is no Orders');
  });

没有返回的函数将返回 'undefined',因此您可以使用 not.toBeUndefined(); 测试它。

简单地期望值是未定义的:

expect(order).toBeUndefined();

Necroposting here, but jest now has toReturn and toReturnWith , without and with arguments assessing, accordingly. And also there are toHaveReturned and toHaveReturnedWith to fit new language.

You can use it on spyOn 'ed variant of your handler :

it("should terminate if there is no order", async () => {
  jest.spyOn(func, "handler")
  console.log = jest.fn();

  let order = await func.handler();
  expect(func.handler).toHaveReturned();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM