javascript - 如何通过 Jest 来兑现这个 promise ?

标签 javascript unit-testing promise mocking jestjs

我用 jest 编写了一个测试来测试我的一个中间件。

const asyncAll = (req, res, next) => {
    const queue = [
        service.exchangeLongTimeToken(req),
        service.retrieveUserInfo(req),
    ];
    Promise.all(queue).then((values) => {
        res.locals.auth = values[0];
        res.locals.user = values[1];
        next();
    }).catch((err) => {
        next(err)
    });
};

测试文件是这样的:

const httpMocks = require('node-mocks-http');
const testData = require('../../testdata/data.json');

describe('Test asyncAll', () => {
    let spy1 = {};
    let spy2 = {};
    const mockNext = jest.fn();

    afterEach(() => {
        mockNext.mockReset();
        spy1.mockRestore();
        spy2.mockRestore();
    });

    test('Should call next() with no error when no error with 2 requests', () => {
        spy1 = jest.spyOn(service, 'exchangeLongTimeToken').mockImplementation((url) => {
            return Promise.resolve(testData.fbLongTimeToken);
        });

        spy2 = jest.spyOn(service, 'retrieveUserInfo').mockImplementation((url) => {
            return Promise.resolve(testData.fbUserInfo);
        });

        const request = httpMocks.createRequest();
        const response = httpMocks.createResponse();

        asyncAll(request, response, mockNext);

        expect(spy1).toBeCalled();
        expect(spy2).toBeCalled();
        expect(mockNext).toBeCalled();
        expect(mockNext).toBeCalledWith();
        expect(mockNext.mock.calls.length).toBe(1);
    });
}

错误是这样的:

Error: expect(jest.fn()).toBeCalled()

Expected mock function to have been called.

  at Object.<anonymous> (tests/backend/unit/fblogin/asyncAll.test.js:39:26)

这反射(reflect)了这一行:

expect(mockNext).toBeCalled();

为什么它没有被调用? 我阅读了有关 jest 的文档,它说我需要返回 promise 才能测试该值。但是asyncAll()并没有返回一个promise,而是消耗了一个promise,如何处理这个问题?

最佳答案

您必须通知 Jest 您在测试中创建的 promise ,请查看 docs关于这个主题:

test('Should call next() with no error when no error with 2 requests', async() => {
        const p1 = Promise.resolve(testData.fbLongTimeToken);
        const p2 = Promise.resolve(testData.fbUserInfo);
        spy1 = jest.spyOn(service, 'exchangeLongTimeToken').mockImplementation((url) => {
            return p1
        });

        spy2 = jest.spyOn(service, 'retrieveUserInfo').mockImplementation((url) => {
            return p2
        });

        const request = httpMocks.createRequest();
        const response = httpMocks.createResponse();

        asyncAll(request, response, mockNext);
        await Promise.all([p1,p2])
        expect(spy1).toBeCalled();
        expect(spy2).toBeCalled();
        expect(mockNext).toBeCalled();
        expect(mockNext).toBeCalledWith();
        expect(mockNext.mock.calls.length).toBe(1);
    });

关于javascript - 如何通过 Jest 来兑现这个 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44411757/

相关文章:

javascript - jQuery - 刷新页面后不起作用

c# - 寻找自定义 SynchronizationContext 的示例(单元测试需要)

angular - 单元测试 ngAfterViewInit

javascript - 等待 async .map() 完成后如何返回推送的数组?

javascript - 如何将 Promises 与 if 结合起来?

javascript - 使用一致的时区解释解析 javascript 日期?

javascript - 正则表达式忽略特定单词的子字符串匹配

javascript - 通过 JavaScript 自动登录到 Alfresco

javascript - Nodeunit 测试基于事件的异步代码

javascript - 不能将原型(prototype)函数放入promise解析中吗?