簡體   English   中英

在Jest中測試回調

[英]Testing a callback in Jest

我有一個繼承的項目,在重構之前要編寫大量測試,並且在測試回調時遇到問題。

static createNew(data) {
        ApiActions.post(
            '/api/projects',
            data,
            (err, response) => {
    // this is the callback I want to test gets triggered
                if (!err) {
                    this.hideCreateNew();
                }
            }
    );
}

ApiActions只是構建並執行ajax請求,第三個參數是回調。

到目前為止我的測試:

import ApiActions from '@helpers/api';
jest.mock('@helpers/api');

...

it('should createNew', () => {
        const callback = jest.fn((cb) => cb());

        Actions.createNew({ data: [] }, callback);

        expect(ApiActions.post).toHaveBeenCalledWith(
            '/api/projects',
            { data: [] },
            expect.any(Function)
        );

        expect(callback).toHaveBeenCalled();
    });

您可以通過將createNew的回調分解為一個單獨的函數並將其用作默認回調,來重構代碼,使其變得更具可測試性,但也可以傳遞其他回調。

我相信應該是這樣的(可能有點錯誤,但是應該可以說明這個想法):

static createCallback(err, response) {
    if (!err) {
        this.hideCreateNew();
    }
}

static createNew(data, callback) {
    // default to createCallback
    callback = callback || createCallback;

    ApiActions.post(
        '/api/projects',
        data,
        callback
    );
}

現在,您可以獨立測試createNewcreateCallback行為是否符合預期。

暫無
暫無

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

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