如何在Jest和TypeScript中测试Azure HTTP触发函数?



我在看这篇文章

https://learn.microsoft.com/en-us/azure/azure-functions/functions-test-a-function javascript-in-vs-code

和我需要测试我的Azure函数之一,写在TypeScript。我在相同的test/中有以下文件文件夹。

DefaultContext.js

module.exports = {
log: jest.fn()
};

GetAnnouncements.test.ts

import httpTrigger from '../GetAnnouncements/index'
const context = require('defaultContext');
test('Get announcements', async () => {
const request = {
query: { name: 'Bill' }
};
await httpTrigger(context, request);
expect(context.log.mock.calls.length).toBe(1);
expect(context.res.body).toEqual('Hello Bill');
});
当我运行npm test第二行是抛出错误
Cannot find module 'defaultContext' from 'tests/GetAnnouncements.test.ts'
However, Jest was able to find:
'./defaultContext.js'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'jsx', 'ts', 'tsx', 'json', 'node'].

这是什么意思?我如何修复这个错误?

我们可以像下面这样传递defaultContext文件路径:

const httpFunction = require('./index');
const context = require('../testing/defaultContext')
test('Http trigger should return known text', async () => {
const request = {
query: { name: 'Bill' }
};
await httpFunction(context, request);
expect(context.log.mock.calls.length).toBe(1);
expect(context.res.body).toEqual('Hello Bill');
});

稍后将此添加到jest配置

"modulePaths": [
"<rootDir>"
],

相关内容

  • 没有找到相关文章

最新更新