【问题标题】:How to test Azure HTTP Trigger Function in Jest and TypeScript?如何在 Jest 和 TypeScript 中测试 Azure HTTP 触发功能?
【发布时间】:2021-12-04 23:33:47
【问题描述】:

我正在关注这篇文章

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

我需要测试一个用 TypeScript 编写的 Azure 函数。我在同一个 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'].

这是什么意思?我该如何解决这个错误?

【问题讨论】:

    标签: typescript azure-functions ts-jest


    【解决方案1】:

    我们可以将下面的 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>"
    ],
    

    【讨论】:

      猜你喜欢
      • 2013-04-11
      • 2020-03-12
      • 2019-11-15
      • 2020-03-27
      • 2020-11-24
      • 1970-01-01
      • 2019-04-24
      相关资源
      最近更新 更多