且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

您如何存根获取api请求

更新时间:2023-01-03 12:56:38

花了一些时间来处理您的代码,直到我意识到问题出在哪里,因为一切看起来都是正确的.实际上,确实如此.除了一件事:您要测试的结果是异步传递的,但是您正在同步地测试它.这意味着您需要将测试更改为异步.

It took some time of playing with your code until I realized what was wrong, because everything looked correct. And in fact, it was. Except for one thing: the result you are testing for is delivered asynchronously, but you are testing for it synchronously. That means you need to change your test to be async.

我假设您使用Mocha作为测试运行程序,它有两种测试异步代码的方法.一种用于任何异步代码的标准方法,以及一种处理Promises的特殊方法.您可以使用适合自己风格的任何东西.

I am assuming you are using Mocha as your test runner, and it has two ways of testing async code. One standard way for any async code, plus one special way of handling Promises. You can use whatever fits your style.

如果您有任何异步代码可以在以后发送结果,则这是通用公式:

If you have any async code where the result is delivered at a later time, this is the general formula:

it('should test an async function', (callback) => {
    const expectedResult = 42;
    doSomethingAsync((result) => {
        try{
            expect(expectedResult).to.equal(result);
            callback();
        } catch(err) {
            callback(err);
        }
    })
});

对于一个承诺返回函数,它看起来像这样:

For a promise returning function this would look like this:

it('should test a promise', (callback) => {
    const expectedResult = 42;
    doSomethingAsync().then((result) => {
        expect(expectedResult).to.equal(result);
        callback();
    }).catch(callback);
});

摩卡(Mocha)具有许诺,可以写出这样的最后一个函数(函数包装器中没有回调!):

Mocha has some sugar for promises making it possible to write the last function like this (no callback in function wrapper!):

it('should test a promise', () => {
    const expectedResult = 42;
    return doSomethingAsync().then((result) => {
        expect(expectedResult).to.equal(result);
    })
});

结论:只需将测试更改为:

return clickTimeseries().then( result => {
    expect(result).to.eq({ 
        success: true,
        data: {stuff: [1,2,3]}
    })
})