执行模拟笑话回调参数

Sha*_*ean 3 javascript jestjs

我需要执行一个参数,它是一个笑话模拟的回调。

在 jest 文档中,他们的回调示例是关于测试第一个回调的。我需要测试嵌套回调中的行为。在 Promise 的例子中,他们使用resolvesrejects。嵌套回调有没有类似的东西?我目前正在执行模拟调用参数,我不确定这是否是推荐的方式。

被测系统:

function execute() {
  globals.request.post({}, (err, body) => {
    // other testable behaviors here.
    globals.doSomething(body);
    // more testable behaviors here. that may include more calls to request.post()
  });
}
Run Code Online (Sandbox Code Playgroud)

考试:

globals.request.post = jest.fn();
globals.doSomething = jest.fn();

execute();

// Is this the right way to execute the argument?
globals.request.post.mock.calls[0][1](null, bodyToAssertAgainst);

expect(globals.doSomething.mock.calls[0][1]).toBe(bodyToAssertAgainst);
Run Code Online (Sandbox Code Playgroud)

我的问题在上面代码的注释中。这是执行回调的推荐方法吗,这是模拟函数的参数?

Hen*_*son 5

由于您不关心您的globals.request.post方法的实现,您需要稍微扩展您的模拟以使您的测试工作。

const bodyToAssertAgainst = {};
globals.request.post = jest.fn().mockImplementation((obj, cb) => {
    cb(null, bodyToAssertAgainst);
});
Run Code Online (Sandbox Code Playgroud)

然后你可以继续期望doSomething被调用bodyToAssertAgainst。此外,通过这种方式,您可以轻松测试您post是否会抛出错误。