简体   繁体   中英

aws-sdk-mock not mocking when using Typescript and ts-jest

I'm having some trouble using the aws-sdk-mock library and Typescript using ts-jest . I'm running the example test from the aws-sdk-mock homepage , shown below. However when I run this test using ts-jest I get the following exception:

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_.-]+

This says to me that the AWS SDK has not been mocked. I have included below the test file, package.json , jest.config.js , jsconfig.json and tsconfig.json .

Any ideas what might be causing this?


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"]
}

I found the answer myself by accident however I do not know why this is the case.

I changed my tsconfig.json , setting esModuleInterop to false and all my problems went away.

{
  "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"]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM