如何通过开玩笑来宣称这个承诺?

时间:2017-06-07 11:46:09

标签: 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);
    });
}

错误是这样的:

  

错误:expect(jest.fn())。toBeCalled()

     

已调用预期的模拟函数。

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

反映了这一行:

expect(mockNext).toBeCalled();

为什么不接听电话? 我阅读有关jest的文档,它说我需要返回promise以测试值。但是asyncAll()没有回复承诺,相反,它会消耗承诺,如何处理这个承诺?

1 个答案:

答案 0 :(得分:0)

您必须通知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);
    });