我想用JEST测试我的express API端点。
下面是我的Express API代码。
routs.ts
// Get release notes
routes.get('/release-notes', (req, res) => {
request.get({
url: 'https://host.com/rest/api/content/search?cql=parent=209266565',
json: true
})
.pipe(res);
});
export default routes;上面的代码将返回数据,但是我想用模拟测试API,而不是发出API请求。
因此,我手动创建了一个模拟响应,并需要用它验证代码。
Mock.ts
export const releaseNotesMockData = {
'results': [
{
'id': '206169942',
'type': 'page',
'status': 'current',
'title': 'Release 2018-10-18 Full Flow CM00294965',
}]
};使用下面的代码,我命中了真正的API,并且测试通过了
describe('Test a 200', () => {
test('It should respond with a 200 status', async () => {
const response = await request(app).get('/release-notes');
expect(response.statusCode).toBe(200);
});
});问题是,我不想使用真正的API进行测试,而是想使用Mocks进行测试。
下面是我尝试过的代码,但它没有工作。请帮帮忙
routs.test.ts
describe('api test', () => {
const url = '/release-notes';
it('user GET should be 200', async () => {
const result = await http({
url,
method: 'get'
});
expect(result).toBe('200');
});
});发布于 2018-12-24 01:59:01
问题是,您没有模拟要导入的request模块。
有关嘲笑的详细信息,请参阅https://jestjs.io/docs/en/tutorial-async。
https://stackoverflow.com/questions/53908027
复制相似问题