Hacker News new | ask | show | jobs
by bloopernova 637 days ago
offtopic: I tried writing some TypeScript, but ran into problems using Jest to test the code. I wanted to write in "up to date" ES6 but I'm not very experienced and wasn't sure which docs or examples to follow.

Should typescript code be written as .mts files, with "type = module" in package.json?

What test layout works best? (i.e. __tests__ in project root? filename.test.mts in the same directory as code?)

Are there any good examples of jest.config.mts (mjs?) and tsconfig.json?

Is the typescript compiler supposed to build the test files too? Is it correct to have a ./build/ in your project root, with all built files including tests under that? Do you then strip out the tests when deploying?

This would be targeting an AWS Lambda environment or similar, not browser based so no bundling, is that correct?

1 comments

Sharing some packages, tsconfig.json, and jest.config.ts I used in a recent project that I'm pretty happy with below (I'm not using `"type": "module"` in my package.json.

Relevant npm packages: - @jest/globals (I use these to import `describe`, `test`, `expect` and other test-related functions) - ts-jest

My tsconfig.json:

  {  
    "buildOptions": {},  
    "compilerOptions": {  
      "target": "ES6",  
      "module": "ESNext",  
      "lib": [  
        "ES6",  
        "DOM",  
        "ES2017",  
        "DOM.Iterable"  
      ],  
      "moduleResolution": "Bundler",  
      "jsx": "react-jsx",  
      "declaration": true,  
      "strict": true,  
      "esModuleInterop": true,  
      "skipLibCheck": true,  
      "forceConsistentCasingInFileNames": true,  
      "outDir": "./dist"  
    },  
    "include": [  
      "src",  
      "__tests__",  
      "*.config.ts",  
      "sandbox.ts",  
      "sandbox-ui.js"  
    ]
  }
and my jest config (jest.config.ts):

  import type { Config } from "jest";

  export default {  
    preset: "ts-jest",  
    testEnvironment: "jsdom",  
    testMatch: ["\*/__tests__/\*/*.test.ts"],  
    globals: {  
      fetch: global.fetch,  
    },  
  } as Config;
I have my tests set up under the `__tests__` directory in project root as you noted, and use a `.test.ts` suffix on all relevant test files. Doing this, ts-jest handles the actual transpilation + execution of the tests (just by running jest), and you don't have to worry about including them in your built solution. I have a separate `tsconfig.build.json` for actually building my project (this... is probably inefficient... but it works well for me :P).
You are a fantastic person, thank you for helping this random internet stranger :) This looks to be exactly what I was after!