1 - UNZIPPED DOWNLOADED ZIP FILE OF POKEMON STARTER CODE
2 - YOUR FOLDER FOR VSC PROJECT
Run the index.ts file to observe the program operation.
Instructions for how to setup the TypeScript Compiler to be able to run `index.ts` in Your TypeScript Project
**Objective**
Guide students through the process of compiling and running `index.ts` in their Pokémon Gym TypeScript application.
Step-by-Step Instructions:
1. **Ensure TypeScript is Installed**:
Verify that TypeScript is installed globally or in your project. Run the following command to check:
```bash
npx tsc --version
```
If TypeScript is not installed, install it globally using: npm install -g typescript
2. Navigate to Your Project Directory
Open your terminal or command prompt and navigate to your project directory:
```bash
cd C:\lab_nov13_jesttests\pokemon-gym
```
Configure TypeScript Operation: To create and set up a configuration file for the TypeScript compiler (`tsc`), you need to create or modify the `tsconfig.json` file in your project. This file is used to specify the root files and compiler options required for compiling the project. Here’s how to create and configure it:
### 1. **Creating a `tsconfig.json` File**
If you don't already have a `tsconfig.json` file in your project, you can create one by running:
```bash
tsc --init
```
This command will create a `tsconfig.json` file with default settings.
### 2. **Basic Structure of `tsconfig.json`**
The generated `tsconfig.json` will look something like this:
```json
{
"compilerOptions": {
"target": "es2016", /* Specify the output JavaScript version */
"module": "commonjs", /* Specify the module code generation */
"outDir": "./dist", /* Specify the output directory for compiled files */
"strict": true, /* Enable strict type-checking options */
"esModuleInterop": true, /* Enable compatibility for importing CommonJS modules */
"resolveJsonModule": true, /* Enable importing JSON files */
"forceConsistentCasingInFileNames": true, /* Enforce consistent file casing */
"skipLibCheck": true /* Skip type checking of declaration files */
},
"include": ["src/**/*"], /* Specify the directory for input TypeScript files */
"exclude": ["node_modules", "dist"] /* Specify files and directories to exclude */
}
```
### 3. **Explanation of Common `tsconfig.json` Fields**
- **`compilerOptions`**: Specifies compiler settings that control how TypeScript is compiled.
- **`target`**: Sets the ECMAScript version for the output. Common options include `es5`, `es6`, `es2016`, `esnext`, etc.
- **`module`**: Specifies the module system. `commonjs` is used for Node.js projects, while `esnext` is used for modern module systems.
- **`outDir`**: Defines the directory where the compiled JavaScript files will be output.
- **`strict`**: Enables all strict type-checking options.
- **`esModuleInterop`**: Facilitates importing CommonJS modules using ES module syntax.
- **`resolveJsonModule`**: Allows JSON files to be imported and used as modules.
- **`forceConsistentCasingInFileNames`**: Ensures that imports use consistent casing across the project.
- **`skipLibCheck`**: Skips type checking of declaration files to speed up compilation.
- **`include`**: Specifies the files or directories that should be included in the compilation.
- **`exclude`**: Specifies files or directories to exclude from the compilation (e.g., `node_modules`).
### 4. **Additional Useful Compiler Options**
- **`sourceMap`**: Generates `.map` files to help with debugging by mapping the compiled JavaScript code back to the TypeScript source.
- **`declaration`**: Generates `.d.ts` declaration files for TypeScript code.
- **`noEmitOnError`**: Prevents emitting output files if there are compilation errors.
- **`lib`**: Specifies a list of built-in TypeScript libraries to include. Examples include `dom`, `es2017`, etc.
- **`noImplicitAny`**: Raises an error when a variable is implicitly assigned an `any` type.
### 5. **Customizing the `tsconfig.json`**
You can further customize your `tsconfig.json` according to your project’s needs. For example, if you want to include specific TypeScript files or add more libraries, update the configuration as needed:
```json
{
"compilerOptions": {
"target": "es2018",
"module": "esnext",
"outDir": "./build",
"strict": true,
"moduleResolution": "node",
"baseUrl": "./",
"paths": {
"@components/*": ["src/components/*"]
},
"resolveJsonModule": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "build"]
}
```
### 6. **Running the TypeScript Compiler**
After configuring your `tsconfig.json`, you can run `tsc` to compile your TypeScript project:
```bash
tsc
```
This command will compile all TypeScript files specified in the `include` section or found in the project directory and output the compiled JavaScript files according to the `outDir` setting.
### Conclusion
Creating and customizing a `tsconfig.json` file is essential for controlling how TypeScript compiles your code. Adjust the configuration as needed for your project requirements and run `tsc` to ensure that your TypeScript code is compiled correctly.
3. Compile TypeScript to JavaScript
Compile the `index.ts` file (and other TypeScript files) into JavaScript using the TypeScript compiler. Run:
npx tsc
This will compile the TypeScript files according to the configurations set in your `tsconfig.json` and generate JavaScript output in your specified `outDir` (e.g., `dist/`).
4. **Locate the Compiled JavaScript File**:
The compiled `index.js` file will typically be located in the `dist/` directory or wherever your `tsconfig.json` specifies. For example:
```
pokemon-gym/dist/index.js
```
5. **Run the Compiled JavaScript File**:
Use Node.js to run the compiled JavaScript:
```bash
node dist/index.js
```
### Troubleshooting Tips:
- **TypeScript Compilation Errors**:
If you encounter errors during TypeScript compilation, check for type mismatches, missing imports, or syntax issues in `index.ts` and other related files.
- **File Not Found Errors**:
Ensure that you have the correct path set for importing modules, especially when using relative paths (e.g., `./services/TrainerService`).
- **Unknown Word Warnings**:
If you see "Unknown word" warnings (as shown in your IDE), these are likely from a spell-check extension and can generally be ignored for the purpose of running TypeScript code.
### Verifying Output:
Once you run `node dist/index.js`, you should see the output of your script in the terminal. If your `index.ts` file includes logic to display data, run tests, or simulate application processes, those results should be printed out accordingly.
---
**Reminder**: Any modifications you make to `index.ts` or related TypeScript files will require you to recompile using `npx tsc` before running the updated JavaScript code with Node.js.
Jest Lab 0: Getting Started
Lab Instruction Book: Creating and Running the Simplest proof of concept Jest Test
Objective: Learn how to write, run, and observe a basic Jest test in their TypeScript project.
{Your job for Assignment 2 is to think how to apply this to your own Code}
Step-by-Step Lab Guide:
1. Setting Up Jest in a TypeScript Project
Navigate to Your Project Directory: Open your terminal and navigate to your project folder:
bash
Copy code
cd C:\lab_nov13_jesttests\pokemon-gym
Install Jest and TypeScript Support: Run the following command to install Jest and TypeScript types for Jest:
npm install --save-dev jest ts-jest @types/jest
Configure Jest for TypeScript: Run this command to create a Jest configuration:
npx ts-jest config:init
This will generate a jest.config.js file in your project folder.
2. Writing Your First Jest Test
(Your Assignment 2 will be to create 4 Jest Tests of relevance to your own code base, and you will make a Traceability Matrix to support your decision as to what to test)
Create a Test File: In the src directory (or src/tests if you have one), create a file named example.test.ts:
// src/tests/example.test.ts
function sum(a: number, b: number): number {
return a + b;
}
describe('Sum Function', () => {
it('should return the correct sum of two numbers', () => {
expect(sum(2, 3)).toBe(5);
});
});
Explanation:
describe block: Groups related tests (in this case, for the sum function).
it block: Defines a single test case with a description.
expect: Checks that the actual result matches the expected result.
3. Running the Jest Test
Run the Test: Execute Jest tests with the following command:
npx jest
Observe the Results: You should see output like:
PASS src/tests/example.test.ts
Sum Function
✓ should return the correct sum of two numbers (5 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.2 s
Ran all test suites.
This indicates that your test ran successfully and passed.
4. Troubleshooting Common Errors
Error Cannot find name 'expect':
Ensure that Jest is properly installed and your TypeScript file is correctly importing Jest types.
Check that @types/jest is listed in devDependencies in package.json.
TypeScript Compilation Errors:
Ensure your tsconfig.json includes:
json
Copy code
{
"compilerOptions": {
"esModuleInterop": true,
"resolveJsonModule": true,
"outDir": "dist"
}
}
5. Analyzing Test Failures
Introduce an Error: Change the function in example.test.ts to return an incorrect result:
typescript
Copy code
function sum(a: number, b: number): number {
return a - b; // Intentional error
}
Re-run the Test: Run npx jest again and observe the failure output:
kotlin
Copy code
FAIL src/tests/example.test.ts
Sum Function
✕ should return the correct sum of two numbers (5 ms)
# Verify setup
npm test
Write-Host "Setup complete! Your Jest testing environment is ready."
"@ | Out-File -FilePath "setup.ps1" -Encoding UTF8
```
## Common PS Commands for Jest Development
```powershell
# Watch for changes
npm run test:watch
# Generate coverage report
npm run test:coverage
# Run specific test file
jest calculator.test.ts
# Clear Jest cache
jest --clearCache
# List all tests without running them
jest --listTests
```
This narrative:
Continues Sarah's story from the previous DevOps materials
Makes testing relatable through real-world scenarios
Introduces key concepts in an engaging way
Sets expectations for what students will learn
Emphasizes the cultural and mindset aspects of testing
Creates continuity with previous learning materials
# The Art of Testing: A DevOps Journey
## Sarah's Next Challenge: Automated Testing
As we rejoin Sarah on her DevOps journey, she faces a new challenge.
Having embraced Git Issues and Actions, she now confronts the critical realm of automated testing.
Dolly, her faithful emotional support dog, sits attentively by her side as Sarah stares at her monitor, pondering the complexities of test automation.
### The Wake-Up Call
It started with a production incident.
A seemingly minor code change had slipped through manual testing, causing the space tourism booking system to accidentally double-book seats on luxury orbital flights.
While quickly fixed, the incident highlighted a crucial gap in their DevOps pipeline: automated testing.
"We can't keep testing everything manually," Sarah announces to her team. "We need robust automated tests that run every time someone pushes code."
Tina, the IT Architect, nods in agreement. "That's where Jest comes in. It's perfect for testing TypeScript applications, and it integrates seamlessly with our GitHub Actions pipeline."
The Testing Epiphany
Sarah's journey into testing automation begins with a simple realization: tests aren't just about catching bugs; they're about confidence.
The purpose of software of Testing is to prevent BUGS (there is more, but this is an acceptable starting point):
What is a BUG? A method call doing something NOT wanted by the SSD.
The goal of software testing is create a topology of all the systemic (method) in the Program that ARE happening: different that what we THINK is happening.
Every test is like a safety net, allowing developers to make changes boldly while ensuring the system's integrity.
"Think of it this way," Brett, the Development Manager, explains, "each test is like a pre-flight check on a spacecraft. You wouldn't launch without going through your checklist, would you?"
Sarah's eyes light up at the aerospace analogy. As someone now deeply involved in space tourism software, this makes perfect sense.
Building the Testing Framework
With renewed enthusiasm, Sarah begins exploring Jest. She discovers it's more than just a testing tool—it's a complete testing ecosystem that provides:
- Intuitive test syntax that reads like plain English
- Powerful mocking capabilities for isolating components
- Built-in code coverage reporting
- Parallel test execution for faster results
- Snapshot testing for UI components
The DevOps Integration
The real power emerges when Sarah integrates Jest into their GitHub Actions pipeline.
"It's like having a tireless QA team working 24/7," Sarah remarks, patting Dolly as she watches the pipeline execute successfully.
### A Cultural Shift
As the team adopts test-driven development (TDD), they notice a cultural shift.
Developers begin thinking about testing from the start, writing more testable code, and catching issues earlier in the development cycle.
"Remember when we used to manually test everything before releases?" Sarah asks during a team meeting. "Now our pipeline catches issues before they even reach code review."
The team's velocity increases, and deployment confidence soars. Even the business stakeholders notice the difference—fewer bugs, faster feature delivery, and more stable releases.
### The Present Day
Fast forward three months: Sarah leads a workshop for new team members on Jest testing best practices.
Dolly still attends every session, now wearing a custom "Test-Driven Development Champion" bandana.
"Testing isn't just about writing tests," Sarah explains to the newcomers. "It's about building quality into every step of our development process. When we push code, we're not hoping it works—we know it works, because our tests tell us so."
Your Testing Journey Begins
As you embark on your own journey into automated testing with Jest and TypeScript, remember Sarah's path.
Like her, you'll discover that testing is not just a technical requirement—it's a mindset, a culture, and a crucial pillar of modern DevOps practices.
In this module, you'll learn:
- How to set up Jest for TypeScript projects
- Writing effective unit tests
- Implementing integration tests (interactions of classes/objects)
- Setting up test automation in GitHub Actions
- Measuring and improving code coverage
- Know what the best practices are for Test-driven development practices
Remember: Every great developer was once a beginner at testing. The key is to start small, build incrementally, and constantly improve your test coverage and quality.
Let's begin this journey together, writing tests that give us the confidence to deploy with peace of mind.
After all, in the words of Sarah: "The best bug is the one that never reaches production because a test caught it first."
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (