我正在使用无服务器框架在 AWS 上构建无服务器 API。我已经使用打字稿模板设置了该项目。默认项目带有一个简单的 hello 处理程序/ lambda 函数。现在我正在尝试为该处理程序编写测试。所以我开始安装 jest。
因此,我在项目的根文件夹中创建了一个包含以下内容的 jest.config.js 文件。
module.exports = {
testEnvironment: "node",
transform: {
"^.+\\.tsx?$": "ts-jest",
},
};
这是 src/functions/hello.handler.ts 中的 hello 处理程序
import {formatJSONResponse, ValidatedEventAPIGatewayProxyEvent} from '@libs/api-gateway';
import { middyfy } from '@libs/lambda';
import schema from './schema';
const hello: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (event) => {
return formatJSONResponse({
message: `Hello ${event.body.name}, welcome to the exciting Serverless world!`,
event,
});
};
export const main = middyfy(hello);
然后我创建了一个 src/tests 目录,并使用以下代码在该目录中创建了一个名为 hello.spec.ts 的文件。
import {main} from "@functions/hello/handler";
import {Context} from "aws-lambda";
describe("hello", () => {
it("should return greeting message", async () => {
const eventMock = {
body: {
name: 'John',
},
// Add other necessary properties for your event
path: '/test',
httpMethod: 'POST',
headers: {
'Content-Type': 'application/json',
},
multiValueHeaders: {},
isBase64Encoded: false,
pathParameters: null,
queryStringParameters: null,
multiValueQueryStringParameters: null,
requestContext: null,
resource: '',
stageVariables: null,
rawBody: JSON.stringify({ name: 'John' }), // Add rawBody property
};
const mockedContext: Context = {
callbackWaitsForEmptyEventLoop: false,
functionName: 'mocked',
functionVersion: 'mocked',
invokedFunctionArn: 'mocked',
memoryLimitInMB: 'mocked',
awsRequestId: 'mocked',
logGroupName: 'mocked',
logStreamName: 'mocked',
getRemainingTimeInMillis(): number {
return 999;
},
done(): void {
return;
},
fail(): void {
return;
},
succeed(): void {
return;
}
};
// Invoke the Lambda function
const result = await main(eventMock, mockedContext, () => {});
console.log(result);
})
})
这是 tsconfig.paths.json 文件。
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@functions/*": ["src/functions/*"],
"@libs/*": ["src/libs/*"],
"@models/*": ["src/models/*"],
"@services/*": ["src/services/*"],
"@tests/*": ["src/tests/*"],
}
}
}
然后我使用此命令运行测试。
jest --config=jest.config.js
我收到此错误。
FAIL src/tests/hello.spec.ts
● Test suite failed to run
Cannot find module '@functions/hello/handler' from 'src/tests/hello.spec.ts'
> 1 | import {main} from "@functions/hello/handler";
| ^
2 | import {Context} from "aws-lambda";
3 |
4 | describe("hello", () => {
at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:427:11)
我的设置有什么问题以及如何修复它?
要在 jest 中使用路径,您需要在 jest 配置中指定它们
module.exports = {
testEnvironment: "node",
moduleNameMapper: {
'@functions/(.*)': '<rootDir>/src/functions/$1',
'@libs/(.*)': '<rootDir>/src/libs/$1',
'@models/(.*)': '<rootDir>/src/models/$1',
'@services/(.*)': '<rootDir>/src/services/$1',
'@tests/(.*)': '<rootDir>/src/tests/$1',
},
transform: {
"^.+\\.tsx?$": "ts-jest",
},
};