经过许多努力,我仍然无法解决这个问题,因此打算寻求帮助。 我正在使用一个中间件在我的node+express应用程序中,看起来像:
import mainConfig from '../mainConfig/index';
const axios = require('axios');
module.exports = {
authHandler: (req, res, next) => {
return mainConfig.initialize().then(() => {
const apiUri = mainConfig.get('app.api');
if (apiUri) {
return axios.get(apiUri).then(response => {
next();
}).catch(error => {
res.redirect('/expired');
throw new Error(error);
});
}
}).catch(() => {
});
}
};
为此,我编写了测试用例,其中我能够模拟axios和我的mainConfig模块。现在,我想测试axios请求解析后是否调用了next()
。有人能帮我吗?
我编写的测试用例是:
import mainConfig from '../mainConfig';
const axios = require('axios');
const middlewares = require('./check-auth');
jest.mock('axios');
describe('Check-Auth Token', () => {
it('should call the Sign In API when live Conf is initalized and have the API URL', () => {
mainConfig.get = jest.fn();
mainConfig.get.mockReturnValue('https://reqres.in/api/users');
mainConfig.initialize = jest.fn(() => Promise.resolve({ data: {} }));
const req = jest.fn(), res = { sendStatus: jest.fn() }, next = jest.fn();
axios.get.mockImplementation(() => Promise.resolve({ data: {} }));
middlewares.authHandler(req, res, next);
expect(next).toHaveBeenCalled(); // coming as not called.
});
});
authHandler
与模拟数据一起正常工作吗?在你的authHandler
中添加一个调试点,再次运行测试,在next();
行之前添加console.log('next has been called');
。 - hoangdv