我开玩笑地编写了一个测试来测试我的中间件。

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);
    });
}


错误是这样的:


  错误:expect(jest.fn())。toBeCalled()
  
  预期的模拟函数已被调用。

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



反映了这一行:

expect(mockNext).toBeCalled();


为什么它不被调用?
我阅读了有关开玩笑的文档,其中说我需要退还诺言才能测试其价值。但是asyncAll()不会返回承诺,而是会消耗一个承诺,该如何处理?

最佳答案

您必须将您在测试中创建的承诺通知给Jest,看看有关此主题的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);
    });

09-25 17:43