【问题标题】:aws-sdk-mock not mocking when using Typescript and ts-jest使用 Typescript 和 ts-jest 时 aws-sdk-mock 不模拟
【发布时间】:2021-06-01 05:36:44
【问题描述】:

我在使用 aws-sdk-mock 库和使用 ts-jest 的 Typescript 时遇到了一些问题。我正在从aws-sdk-mock homepage 运行示例测试,如下所示。但是,当我使用 ts-jest 运行此测试时,出现以下异常:

ValidationException: 2 validation errors detected: Value '' at 'tableName' failed to satisfy constraint: Member must have length greater than or equal to 3; Value '' at 'tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+

这告诉我 AWS 开发工具包没有被模拟。我在测试文件下面包含了package.jsonjest.config.jsjsconfig.jsontsconfig.json

任何想法可能导致这种情况?


demo.test.ts

import * as AWSMock from 'aws-sdk-mock';
import * as AWS from 'aws-sdk';
import { GetItemInput } from 'aws-sdk/clients/dynamodb';

beforeAll(async (done) => {
  //get requires env vars
  done();
});

describe.only('the module', () => {
  it('should mock getItem from DynamoDB', async () => {
    // Overwriting DynamoDB.getItem()
    AWSMock.setSDKInstance(AWS);
    AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => {
      console.log('DynamoDB', 'getItem', 'mock called');
      callback(null, { pk: 'foo', sk: 'bar' });
    });

    let input: GetItemInput = { TableName: '', Key: {} };
    const dynamodb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });
    expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' });

    AWSMock.restore('DynamoDB');
  });
});


package.json

{
  "name": "test-project",
  "version": "1.0.0",
  "description": "",
  "main": "app.ts",
  "repository": "",
  "author": "",
  "license": "MIT",
  "private": true,
  "scripts": {
    "test": "NODE_ENV=test jest",
  },
  "devDependencies": {
    "@types/aws-lambda": "^8.10.71",
    "@types/axios": "^0.14.0",
    "@types/jest": "^26.0.20",
    "@types/node": "^14.14.25",
    "@types/uuid": "^8.3.0",
    "aws-sdk": "^2.841.0",
    "aws-sdk-mock": "^5.1.0",
    "jest": "^26.6.3",
    "ts-jest": "^26.5.1",
    "typescript": "^4.1.5"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "dotenv": "^8.2.0",
    "uuid": "^8.3.2"
  }
}


jest.config.js

module.exports = {
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(tsx?)$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};


jsconfig.json

{ "typeAcquisition": { "include": [ "jest" ] } }

tsconfig.json

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
    "target": "es2017",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "outDir": "./dist/",                        /* Redirect output structure to the directory. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  },
  "include": ["src/*.ts", "__tests__/**/*.ts"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

【问题讨论】:

    标签: node.js typescript amazon-web-services unit-testing jestjs


    【解决方案1】:

    我自己偶然找到了答案,但我不知道为什么会这样。

    我更改了我的tsconfig.json,将esModuleInterop 设置为false,我的所有问题都消失了。

    {
      "compilerOptions": {
        /* Visit https://aka.ms/tsconfig.json to read more about this file */
        "target": "es2017",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
        "outDir": "./dist/",                        /* Redirect output structure to the directory. */
        "strict": true,                           /* Enable all strict type-checking options. */
        "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
        "esModuleInterop": false,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
        "skipLibCheck": true,                     /* Skip type checking of declaration files. */
        "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
      },
      "include": ["src/*.ts", "__tests__/**/*.ts"],
      "exclude": ["node_modules", "**/*.spec.ts"]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      • 2020-08-13
      • 1970-01-01
      • 2022-09-30
      相关资源
      最近更新 更多