### Install Soda-Test Source: https://github.com/ranhs/soda-test/wiki/03-getting-started Installs the soda-test package as a development dependency using npm. This command should be run in your Node.js project's root directory. ```Bash npm install soda-test --save-dev ``` -------------------------------- ### Install Soda-Test for Angular Source: https://github.com/ranhs/soda-test/wiki/03.2-getting-started-karma Installs the Soda-Test package as a development dependency in your Angular project using npm. This is the first step to enable Soda-Test's unit testing capabilities. ```bash npm install soda-test --save-dev ``` -------------------------------- ### Basic Soda-Test Example Source: https://github.com/ranhs/soda-test/wiki/03-getting-started A basic unit test written in TypeScript using Soda-Test. It demonstrates how to use the 'describe' and 'it' decorators to define a test suite and individual test cases, and uses 'expect' for assertions. ```TypeScript import { expect, describe, it, TR } from 'soda-test' @describe('Basic Sample') class SampleCase { @it('validates that 1+1 is 2') sampleStep(): TR { expect(1+1).to.equal(2) } } ``` -------------------------------- ### Getting Started with Soda Test using Mocha Source: https://github.com/ranhs/soda-test/blob/main/README.md This guide explains how to set up and use Soda Test with Mocha for testing NodeJS projects. It assumes basic knowledge of TypeScript. ```TypeScript // Example usage with Mocha (specific code not provided in text, refer to wiki) ``` -------------------------------- ### Run Tests with npm Source: https://github.com/ranhs/soda-test/wiki/03-getting-started Commands to execute the configured tests using npm. Running 'npm run test' or 'npm test' will trigger Mocha to find and run the test files as specified in the package.json scripts section. ```Bash npm run test ``` ```Bash npm test ``` -------------------------------- ### Getting Started with Soda Test using Karma Source: https://github.com/ranhs/soda-test/blob/main/README.md This section covers the setup for using Soda Test with Karma, primarily for testing Angular projects. Familiarity with TypeScript is necessary. ```TypeScript // Example usage with Karma and Angular (specific code not provided in text, refer to wiki) ``` -------------------------------- ### Configure npm Test Script Source: https://github.com/ranhs/soda-test/wiki/03-getting-started Configures the 'test' script in your project's package.json to use Mocha for running tests. This example specifies that Mocha should execute any file ending with '.test.js' in the project, including those in subdirectories. ```JSON { ... "scripts": { "test": "mocha \"./{,!(node_modules)/**}/*.test.js\"" ... } ... } ``` -------------------------------- ### Install Jest Dependencies Source: https://github.com/ranhs/soda-test/wiki/03.1-getting-started-jest Installs Jest and related packages as development dependencies for Angular unit testing. ```bash npm install jest jest-preset-angular @types/jest -D ``` -------------------------------- ### Getting Started with Soda Test using Jest Source: https://github.com/ranhs/soda-test/blob/main/README.md This guide details the process of integrating Soda Test with Jest, specifically for testing Angular projects. It requires TypeScript knowledge. ```TypeScript // Example usage with Jest and Angular (specific code not provided in text, refer to wiki) ``` -------------------------------- ### Example Test Case with Rewiring Source: https://github.com/ranhs/soda-test/wiki/13-rewire Provides a complete example of a test case using soda-test and rewire. It demonstrates setting a private variable, getting its value, modifying it, and verifying the changes using assertions. ```TypeScript import {describe, context, it, TR, expect, rewire, Rewire} from 'soda-test' import {getCount, setCount} from './lib' @describe("TestTest") class TestTest { beforeEach(): void { setCount(18) } @context("rewire") @it("should rewire lib as argument") checkRewire1(@rewire('./lib') libRewire: Rewire): TR { const count = libRewire.get('_count') expect(count).to.equal(18) libRewire.set('_count', 222) expect(getCount()).to.equal(222) libRewire.set('getCount', ()=>libRewire.get('_count')+1) expect(getCount()).to.equal(223) } @it("should reset rewire changes") checkRewire1After(): TR { expect(getCount()).to.equal(18) } } ``` -------------------------------- ### npm Installation Command Source: https://github.com/ranhs/soda-test/blob/main/README.md Provides the command to install the soda-test package as a development dependency using npm. This is the standard way to add the package to a project for testing purposes. ```bash npm install soda-test --save-dev ``` -------------------------------- ### TypeScript API Test Case with Steps Source: https://github.com/ranhs/soda-test/blob/main/README.md Illustrates defining API test cases using the `@testCase` decorator in TypeScript. The example shows how to define test steps within a method, such as starting a dummy REST server, sending requests, and validating responses. This approach allows for structured and reusable API testing scenarios. ```TypeScript @testCase("sample case", SampleTestStepsTest) checkGetApi(step: stepMethod): void { step("define dummy REST server").StartRestServer({expect: "GET /", return: "dummy"}) step("send get request").SendRequest({method:"GET", url: "/", expectresponse: "dummy"}) step("validate get request").ValidateRequest({method: "GET", url: "/"}) step("stop dummy Rest server").StopRestServer() } ``` -------------------------------- ### TypeScript: Basic Function Example Source: https://github.com/ranhs/soda-test/wiki/11-stubs A simple TypeScript function that logs messages to the console. This serves as a basic example for demonstrating stubbing. ```TypeScript export function foo() { // some operation console.log('console.log was called') console.warn('console.warn was called') return } ``` -------------------------------- ### Configure Angular to use Soda-Test Karma Builder Source: https://github.com/ranhs/soda-test/wiki/03.2-getting-started-karma Modifies the `angular.json` file to replace the default Angular Karma builder with the Soda-Test Karma builder. This change allows Soda-Test to manage the testing environment. ```json { ... "projects": { "my-app": { ... "architect": { ... "test": { "builder": "soda-test:karma", ... }, ... } } }, "defaultProject": "my-app" } ``` -------------------------------- ### Checking for Specific Values (null, undefined, boolean, empty) Source: https://github.com/ranhs/soda-test/wiki/20-expect Provides examples for asserting specific JavaScript values like `null`, `undefined`, `true`, `false`, and checking if an object or array is empty using Chai's built-in properties. ```javascript expect(result).to.equal(null) expect(result).to.be.null expect(result2).to.not.be.null expect(false).to.be.false expect(true).to.be.true expect(null).to.be.null expect(undefined).to.be.undefined expect({}).to.be.empty expect([]).to.be.empty expect(undefined).to.not.exist expect(null).to.not.exist ``` -------------------------------- ### Define Express App Source: https://github.com/ranhs/soda-test/wiki/15-supertest This snippet shows the basic setup of an Express application in TypeScript, including middleware for URL-encoded and JSON request bodies. It defines a simple GET route for the root path. ```typescript import * as express from 'express' import { Express } from 'express' import { urlencoded, json } from 'body-parser' export const app: Express = express() app.use(urlencoded({ extended: true })) app.use(json()) //-----------------------------------> routes app.get('/', (req, res) => { res.status(200).json({ name: 'Foo Fooing Bar' }) }) ``` -------------------------------- ### Jest Configuration (jest.config.js) Source: https://github.com/ranhs/soda-test/wiki/03.1-getting-started-jest Configures Jest for Angular projects, specifying the preset, test file locations, setup files, coverage options, and module name mapping. ```javascript const { pathsToModuleNameMapper } = require('ts-jest') const { compilerOptions } = require('./tsconfig') module.exports = { preset: 'jest-preset-angular', roots: ['./src'], testMatch: ['demo.spec.ts', '**/+(*.)+(spec).+(ts)'], setupFilesAfterEnv: ['./src/test.ts'], collectCoverage: true, verbose: true, coverageReporters: ['html'], coverageDirectory: '../coverage-ut/front-end', moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, { prefix: './' }) } ``` -------------------------------- ### TypeScript: Global Decorator Example Source: https://github.com/ranhs/soda-test/wiki/21-global Shows the application of the @global() decorator before a Sinon.JS decorator in TypeScript. This setup ensures that the decorated sinon (spy, stub, etc.) is created and released only once for the entire scope, persisting its state across multiple test steps. ```TypeScript @global() @stub(testObject, 'func2').returns(222) func2Stub2: SinonStub ``` -------------------------------- ### TypeScript Test Class Setup with Soda Test Source: https://github.com/ranhs/soda-test/wiki/04-describe-it This TypeScript code demonstrates the basic structure for a test class using the 'soda-test' library. It includes importing the 'describe' decorator and applying it to the test class. ```ts import { describe } from 'soda-test' @describe('demo') class TestDemo { } ``` -------------------------------- ### Customizing Soda-Test Abilities with Configuration Source: https://github.com/ranhs/soda-test/blob/main/README.md This guide explains how to use the Soda Test configuration file to customize various aspects and abilities of the framework according to your project's needs. ```TypeScript // Example of configuration file usage (specific code not provided in text, refer to wiki) ``` -------------------------------- ### Spy/Stub Called With Specific Arguments Source: https://github.com/ranhs/soda-test/wiki/20-expect Demonstrates how to assert that a Sinon spy or stub was called with a specific set of arguments. ```javascript expect(methodSpy).to.have.been.calledWith(args) expect(methodStub).to.have.been.calledWith(args) ``` -------------------------------- ### Numeric Comparison with below/lessThan Source: https://github.com/ranhs/soda-test/wiki/20-expect Demonstrates asserting that a number is strictly less than another number using `below` or its synonym `lessThan`. This assertion is applicable to numbers and Dates. ```javascript expect(value1).to.be.below(value2) expect(2).to.be.below(3) expect(2).to.be.lessThan(3) ``` -------------------------------- ### Basic Integration Test Setup (TypeScript) Source: https://github.com/ranhs/soda-test/wiki/25-integrationtest Sets up a basic integration test for an Angular component using Soda-Test's testing utilities. It includes importing necessary modules and decorators, defining a test class, and initializing the component and fixture in a beforeEach block. ```TypeScript import { describe, it, expect, TR, ComponentFixture, TestBed } from 'soda-test' import { TestComponent } from './test.component' @describe('Test Component') class TestComponentTest { component: TestComponent fixture: ComponentFixture beforeEach(): void { this.fixture = TestBed.createComponent(TestComponent) this.component = this.fixture.componentInstance this.fixture.detectChanges() } @it('should create') validateCreate(): TR { expect(this.component).to.exist } } ``` -------------------------------- ### Running Test Code in a Sandbox Source: https://github.com/ranhs/soda-test/blob/main/README.md This guide explains how to execute your test code within a 'Sandbox' environment using Soda Test. Sandboxing helps in isolating test runs and preventing side effects. ```TypeScript // Example of using sandbox (specific code not provided in text, refer to wiki) ``` -------------------------------- ### Numeric Comparison with above/greaterThan Source: https://github.com/ranhs/soda-test/wiki/20-expect Shows how to assert that a number is strictly greater than another number using `above` or its synonym `greaterThan`. This works for numbers and Dates. ```javascript expect(value1).to.be.above(value2) expect(2).to.be.above(1) expect(2).to.be.greaterThan(1) ``` -------------------------------- ### Check Object Instance with instanceof Source: https://github.com/ranhs/soda-test/wiki/20-expect Demonstrates how to use `instanceof` to assert that an object is an instance of a specific class or its subclass. It also shows chaining assertions for type and properties. ```typescript class A {a: number = 1} class B extends A {b: number = 2} ...expect(new A()).to.be.instanceOf(A) expect(new B()).to.be.instanceOf(B) expect(new B()).to.be.instanceOf(A) expect(new A()).to.not.be.instanceOf(B) expect(new A()).to.be.instanceOf(A).to.be.an('object').to.have.property('a',1) ``` -------------------------------- ### Using Control Methods for Test Execution Flow Source: https://github.com/ranhs/soda-test/blob/main/README.md This section explains the use of 'Control Methods' in Soda Test to define setup and teardown logic, such as actions to perform before/after each test method or all tests within a class or context. ```TypeScript // Example of control methods (specific code not provided in text, refer to wiki) ``` -------------------------------- ### Testing Asynchronous Methods Returning Promises Source: https://github.com/ranhs/soda-test/blob/main/README.md This guide focuses on testing asynchronous functions that return Promises. Soda Test provides mechanisms to effectively manage and assert the outcomes of Promise-based operations. ```TypeScript // Example of async testing with Promises (specific code not provided in text, refer to wiki) ``` -------------------------------- ### TypeScript: Stubbing the Main Library Method Source: https://github.com/ranhs/soda-test/wiki/11-stubs Explains how to stub the main export or default method of a library by passing only the library name to the `@stub` decorator. Includes examples of importing the library itself or its default export. ```TypeScript @stub('parse-function') parseFuncStub: SinonStub ``` -------------------------------- ### Full Test Component Spec Source: https://github.com/ranhs/soda-test/wiki/25-integrationtest Provides a complete example of a test file (test.component.spec.ts) for an Angular component using soda-test. It includes imports, interface definitions, stub components, fixture configuration, and test methods with spies. ```TypeScript import { describe, it, expect, TR, SodaFixture, fixture, component, CommonEvents, spy, SinonSpy } from 'soda-test' import { TestComponent } from './test.component' import { Component } from '@angular/core' interface MyEvents extends CommonEvents { ievent(data: any): void } @Component({selector: 'mycomponent'}) class MyComponentStub { } @describe('Test Component') class TestComponentTest { @fixture(TestComponent, { declarations: [MyComponentStub], events: ['ievent'] }) fixture: SodaFixture @component(TestComponent) component: TestComponent @it('call onMyComponentEvent() method of the event data when ievent is raised from mycomponent') eventWasCalled( @spy(TestComponent.prototype, 'onMyComponentEvent') onMyComponentEventSpy: SinonSpy): TR { const mycomponent = this.fixture.queryByCss('mycomponent') mycomponent.triggerEventHandler.ievent("test-data") expect(onMyComponentEventSpy).to.have.been.calledWithExactly('test-data') } } ``` -------------------------------- ### Stub Getter and Setter with Callback Source: https://github.com/ranhs/soda-test/wiki/11-stubs This example illustrates stubbing both a getter and a setter for 'Value' on 'DummyClass' from './lib'. The getter returns undefined, and the setter calls a callback function with the value being set, storing it in `TestTest._v`. ```ts import { SinonStub } from 'sinon'; // Assuming './lib' exports DummyClass // Assuming DummyClass has a getter/setter named 'Value' // Assuming TestTest is a globally accessible object or imported // @stub('./lib', 'DummyClass', 'Value').access(undefined, (v: number) => { TestTest._v = v }) // valueStub: SinonStub; ``` -------------------------------- ### Check Method Calls with Arguments (TypeScript) Source: https://github.com/ranhs/soda-test/wiki/20-expect Asserts that a SinonSpy or SinonStub was called with the specified arguments. It supports checking for exact argument matches and can verify the number of times the method was called. ```TypeScript @it('should call demo1 with expected arguments') callDemo( @spy(ExpectTest, 'demo1') demo1Spy: SinonSpy): TR { ExpectTest.demo1(12,"a") expect(demo1spy).to.have.been.calledWith(12,"a") expect(demo1spy).to.have.been.calledOnce.calledWith(12) ExpectTest.demo1(13,"b") expect(demo1spy).to.have.been.calledWith(12,"a").calledWith(13,"b").calledTwice } ``` -------------------------------- ### Full Test Component Spec Source: https://github.com/ranhs/soda-test/wiki/25-integrationtest Provides a complete test file (test.component.spec.ts) for an Angular component using Soda Test. It includes imports, component stubs, fixture setup, and a test case for attribute binding. ```ts import { describe, it, expect, TR, SodaFixture, fixture, component } from 'soda-test' import { TestComponent } from './test.component' import { Component, Input } from '@angular/core' @Component({selector: 'mycomponent'}) class MyComponentStub { @Input() ikey: string } @describe('Test Component') class TestComponentTest { @fixture(TestComponent, { declarations: [MyComponentStub] }) fixture: SodaFixture @component(TestComponent) component: TestComponent @it('binds the mycomponentkey member to the ikey attribute on mycomponent') attributeWasUpdated(): TR { const mycomponent = this.fixture.queryByCss('mycomponent') this.component.mycomponentkey = "test-key-value" this.fixture.detectChanges() expect(mycomponent.attributes.ikey).to.equal('test-key-value') } } ``` -------------------------------- ### TypeScript Test Assertion with Soda Test and Chai Source: https://github.com/ranhs/soda-test/wiki/04-describe-it This TypeScript code provides a complete example of a test step using 'soda-test' and 'chai' assertions. It imports the function to be tested and uses 'expect' to validate the result. ```ts import { expect, describe, it, TR } from 'soda-test' import { add } from './demo' @describe('demo') class TestDemo { @it('should add two numbers') addBasic(): TR { expect(add(1,2)).to.equal(3) } } ``` -------------------------------- ### Test Promise with Async/Await Source: https://github.com/ranhs/soda-test/wiki/06-Asynchronous-test-step-with-Promise This example demonstrates testing a Promise-returning method using async/await in a test step. The test step is defined as `async`, allowing the use of `await` to wait for the Promise to resolve. Rejected Promises in the tested method will cause the test step to fail. ```typescript @it('should test a promise with async await') async addWithAsyncAwait(): PTR { let result: number = await addPromise(1,2) expect(result).to.equal(3) } ``` -------------------------------- ### Test Promise with Chai-as-Promise (Rejected) Source: https://github.com/ranhs/soda-test/wiki/06-Asynchronous-test-step-with-Promise This example shows how to test a rejected Promise scenario using `chai-as-promise`. It asserts that the Promise returned by `dividePromise(4,0)` will be rejected with a specific error message. The `await` keyword is necessary before `expect`. ```typescript @it('should fail to divide by 0') async divideFails(): PTR { await expect(dividePromise(4,0)).to.eventually.rejectedWith('cannot divide by 0') } ``` -------------------------------- ### Query Element by CSS Selector Source: https://github.com/ranhs/soda-test/wiki/25-integrationtest Demonstrates how to find an inner element using a CSS selector with the query.by.css method or its shorthand queryByCss. It shows examples for finding elements by class, attribute, and tag name. ```TypeScript const deContent = this.fixture.debugElement.query.by.css('.content') const deContent = this.fixture.queryByCss('.content') const a1 = this.fixture.queryByCss('[id=a1]') const mc = this.fixture.queryByCss('mycomponent') ``` -------------------------------- ### SodaFixture and @component Decorators (TypeScript) Source: https://github.com/ranhs/soda-test/wiki/25-integrationtest Demonstrates using Soda-Test's @fixture and @component decorators to automatically inject the SodaFixture and component instance as class members. This simplifies the setup by eliminating the need for manual fixture creation in beforeEach. ```TypeScript import { describe, it, expect, TR, SodaFixture, fixture, component } from 'soda-test' import { TestComponent } from './test.component' @describe('Test Component') class TestComponentTest { @fixture(TestComponent) fixture: SodaFixture @component(TestComponent) component: TestComponent @it('should create') validateCreate(): TR { expect(this.component).to.exist } } ``` -------------------------------- ### Insert Variables into Files with Soda-test Rewire Source: https://github.com/ranhs/soda-test/wiki/24-configuration This example demonstrates how to use the 'rewire' configuration to insert new variables into specific files. The 'insertVars' property within the 'files' object allows you to define variables to be added to a target file, which can then be manipulated using rewire methods. ```json { "rewire": { "files": { "lib/config": { "insertVars": [ { "name": "kuku" }, { "name": "foo" } ] } } } } ``` -------------------------------- ### Configure Package.json Scripts for Soda-Test Source: https://github.com/ranhs/soda-test/wiki/03.1-getting-started-jest Sets the 'test' script in `package.json` to use `soda-test`'s Jest starter for running tests. ```json { ... "scripts": { "test": "node node_modules/soda-test/jest.js" ... } ... } ``` -------------------------------- ### TypeScript: Organize Tests with Contexts and Steps Source: https://github.com/ranhs/soda-test/wiki/07-context Demonstrates how to use `@describe`, `@context`, and `@it` decorators in TypeScript to define test suites, group test steps into logical contexts, and specify individual test cases. This example covers basic assertions, callback-based asynchronous tests, and Promise-based asynchronous tests using async/await. ```TypeScript import { expect, describe, context, it, TR, PTR, Done } from 'soda-test' import { add, addCallbck, addPromise, dividePromise } from './demo' @describe('demo') class TestDemo { @context('add') @it('should add two numbers') addBasic(): TR {...} @context('callback add') @it('should test the callback') addWithCallback(done: Done): TR {...} @context('test promise') @it('should add with promise cb') addWithPromise(done: Done): TR {...} @it('should test a promise with return') addReturnAPromise(): Promise {...} @it('should test a promise with async await') async addWithAsyncAwait(): PTR {...} @it('should test a promise with chai-as-promise') async addWithChaiAsPromise(): PTR { @context('divide') @it('should test a promise with chai-as-promise (divide success)') async divideSuccess(): PTR {...} @it('should test a promise with chai-as-promise (divide fails)') async divideFails(): PTR {...} } ``` -------------------------------- ### Instantiate Class with New Keyword Source: https://github.com/ranhs/soda-test/wiki/18-creatableclass Demonstrates the standard way to create an instance of a class using the 'new' keyword and passing arguments to its constructor. ```ts const obj = new MyClass("Me", 17) ``` -------------------------------- ### Get Element Text using DebugElement Source: https://github.com/ranhs/soda-test/wiki/25-integrationtest Explains two ways to get the text content of an element: directly accessing the `text` property of the SodaDebugElement, or by accessing the `innerText` of the `nativeNode`. ```TypeScript const p = this.fixture.queryByCss('p') expect(p.nativeNode.innerText).to.equal('test.component works!') expect(p.text).to.equal('test.component works!') ``` -------------------------------- ### Test Express GET Route Source: https://github.com/ranhs/soda-test/wiki/15-supertest This TypeScript snippet demonstrates how to test a GET route ('/') of an Express application using Soda-Test and Supertest. It makes a request to the route, asserts the expected status code (200), and validates the response body. ```typescript import { expect, describe, it, TR, request } from 'soda-test' import { app } from './app' @describe('app') class AppTest { @context('GET /') @it('should get /') async testGet1(): PTR { const response = await request(app).get('/').expect(200) expect(response.body).to.have.property('name').to.equal('Foo Fooing Bar') } } ``` -------------------------------- ### Spy/Stub Called At Least Once Source: https://github.com/ranhs/soda-test/wiki/20-expect Shows how to assert that a Sinon spy or stub has been called at least once. The `to.have.been` prefix is optional. ```typescript @it('should call demo') callDemo( @spy(ExpectTest, 'demo') demoSpy: SinonSpy): TR { expect(demospy).to.not.have.been.called ExpectTest.demo() expect(demospy).to.have.been.called ExpectTest.demo() ExpectTest.demo() expect(demospy).to.have.been.called.calledThrice ``` -------------------------------- ### Chai Expect to.be.instanceOf Source: https://github.com/ranhs/soda-test/wiki/20-expect Validates if an object is an instance of a specific class type. This is useful for checking constructor relationships. ```typescript expect(objectInstance).to.be.instanceOf(classType) ``` -------------------------------- ### TypeScript Unit Test with Decorators Source: https://github.com/ranhs/soda-test/blob/main/README.md Demonstrates how to write unit tests in TypeScript using Soda-Test decorators like `@describe` and `@it`. It shows how to use Sinon stubs for dependency injection via class members, with automatic cleanup handled by the package. The example tests a `getUser` function and verifies stub interactions. ```TypeScript @describe('demo') class TestDemoTest { @stub(User, "findById").returns("dummy-user") findStub: SinonStub @it('should get user by id') GetById(): TR { const user = getUser({id:123}) expect(user).to.equal("dummy-user") expect(this.findStub).to.have.been.calledOnce.calledWith(123) } } ``` -------------------------------- ### Negated Assertions with 'not' Source: https://github.com/ranhs/soda-test/wiki/20-expect Illustrates the use of the `not` property in Chai assertions. When `not` precedes a condition, the assertion passes if the condition is not met. ```javascript expect(2).to.equal(2) expect(3).to.not.equal(2) expect({a:2}).to.deep.equal({a:2}) expect({a:2,b:3}.to.not.deep.equal({a:2}) ``` -------------------------------- ### Spy/Stub Called Exactly Once Source: https://github.com/ranhs/soda-test/wiki/20-expect Shows how to assert that a Sinon spy or stub has been called exactly one time. The `to.have.been` prefix can be omitted. ```typescript @it('should call demo once') callDemo( @spy(ExpectTest, 'demo') demoSpy: SinonSpy): TR { ExpectTest.demo() expect(demospy).to.have.been.calledOnce expect(demospy).to.have.been.calledOnce.calledOnce ``` -------------------------------- ### Configure soda-plan in package.json Source: https://github.com/ranhs/soda-test/wiki/23-testplan This snippet shows how to add the 'soda-plan' script to your package.json file. This script uses Node.js to run the soda-test plan generator, specifying the input test files using a regular expression and the output test plan file name. ```json { "scripts": { "soda-plan": "node node_modules/soda-test/plan \"dist/test-samples/**/*.test.js\" testPlan.json" } } ``` -------------------------------- ### Check Promise Rejection (TypeScript) Source: https://github.com/ranhs/soda-test/wiki/20-expect Asynchronously asserts that a promise is rejected. It waits for the promise to settle and validates that it was rejected, failing if it resolves instead. ```TypeScript await expect(promise).to.eventually.be.rejected ``` ```TypeScript await expect( Promise.reject() ).to.eventually.be.rejected await expect( Promise.reject(12) ).to.eventually.be.rejected.to.equal(12) const rv = await expect( Promise.reject(12) ).to.eventually.be.rejected expect(rv).to.equal(12) ``` -------------------------------- ### Uninstall Karma Dependencies Source: https://github.com/ranhs/soda-test/wiki/03.1-getting-started-jest Removes Karma and related testing packages from the project dependencies. ```bash npm uninstall karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter ``` -------------------------------- ### Check Promise Fulfillment (TypeScript) Source: https://github.com/ranhs/soda-test/wiki/20-expect Asynchronously checks if a promise resolves successfully. It awaits the promise and asserts that it is not rejected. The assertion can be chained with other matchers. ```TypeScript await expect(promise).to.eventually.be.fulfilled ``` ```TypeScript await expect( Promise.resolve() ).to.eventually.be.fulfilled await expect( Promise.resolve() ).to.eventually.be.fulfilled.fulfilled const rv = await expect( Promise.resolve(12) ).to.eventually.be.fulfilled expect(rv).to.equal(12) ``` -------------------------------- ### Configure src/test.ts for Jest Source: https://github.com/ranhs/soda-test/wiki/03.1-getting-started-jest Modifies the `src/test.ts` file to set up necessary browser environment mocks for Jest to run Angular tests, including CSS and document object mocks. ```typescript import 'jest-preset-angular' Object.defineProperty(window, 'CSS', { value: null }) Object.defineProperty(window, 'getComputedStyle', { value: () => { return { display: 'none', appearance: ['-webkit-appearance'] } } }) Object.defineProperty(document, 'doctype', { value: '' }) Object.defineProperty(document.body.style, 'transform', { value: () => { return { enumerable: true, configurable: true } } }) ``` -------------------------------- ### Spy/Stub Called Exactly Thrice Source: https://github.com/ranhs/soda-test/wiki/20-expect Illustrates asserting that a Sinon spy or stub has been called exactly three times. The `to.have.been` prefix can be omitted. ```typescript @it('should call demo 3 times') callDemo( @spy(ExpectTest, 'demo') demoSpy: SinonSpy): TR { ExpectTest.demo() ExpectTest.demo() ExpectTest.demo() expect(demospy).to.have.been.calledThrice expect(demospy).to.have.been.calledThrice.not.calledOnce ``` -------------------------------- ### Spy/Stub Called Exactly Twice Source: https://github.com/ranhs/soda-test/wiki/20-expect Demonstrates asserting that a Sinon spy or stub has been invoked precisely two times. The `to.have.been` prefix is optional. ```typescript @it('should call demo twice') callDemo( @spy(ExpectTest, 'demo') demoSpy: SinonSpy): TR { ExpectTest.demo() ExpectTest.demo() expect(demospy).to.have.been.calledTwice expect(demospy).to.have.been.calledTwice.not.calledOnce ``` -------------------------------- ### Running Integration/Component Tests Source: https://github.com/ranhs/soda-test/blob/main/README.md This section covers using Soda Test for integration and component testing, specifically focusing on testing component bindings to HTML elements. ```TypeScript // Example of integration/component testing (specific code not provided in text, refer to wiki) ``` -------------------------------- ### Generating Test JSON Documents with Test Plan Source: https://github.com/ranhs/soda-test/blob/main/README.md Learn how to use Soda Test's 'Test Plan' functionality to generate a JSON document that outlines your test suite. This can be useful for reporting and analysis. ```TypeScript // Example of generating test plan JSON (specific code not provided in text, refer to wiki) ``` -------------------------------- ### Using Describe and It Decorators for Unit Testing Source: https://github.com/ranhs/soda-test/blob/main/README.md Learn how to utilize the 'describe' and 'it' decorators in Soda Test to structure and define simple unit tests. This is a fundamental aspect of building tests with the framework. ```TypeScript // Example of describe/it decorators (specific code not provided in text, refer to wiki) ``` -------------------------------- ### Check Promise Equality (TypeScript) Source: https://github.com/ranhs/soda-test/wiki/20-expect Asynchronously verifies that a promise resolves with a specific value. It waits for the promise to resolve and then compares the resolved value against the expected value. ```TypeScript await expect(promise).to.eventually.be.euqal(value) ``` ```TypeScript await expect( Promise.resolve(12)).to.eventually.be.equal(12) await expect( Promise.resolve(12)).to.eventually.be.equal(12).fulfilled const rv = await expect( Promise.resolve(12) ).to.eventually.be.equal(12) expect(rv).to.equal(12) ``` -------------------------------- ### Chai Expect to.not.equal Source: https://github.com/ranhs/soda-test/wiki/20-expect Validates if two values are not strictly equal. For reference types, it checks if they refer to different objects. The checked value is the second argument. ```typescript expect(value1).to.not.equal(value2) ``` ```typescript expect(3).to.not.equal(2).to.equal(2) expect({}).to.not.equal({}) ``` -------------------------------- ### Execute Test Plan Generation Source: https://github.com/ranhs/soda-test/wiki/23-testplan This command executes the 'soda-plan' script defined in the package.json. It triggers the soda-test tool to generate the test plan JSON file based on the configured input files and output file name. ```bash npm soda-plan ``` -------------------------------- ### Chai Expect to.equal Source: https://github.com/ranhs/soda-test/wiki/20-expect Validates if two values are strictly equal. For reference types, it checks if they refer to the same object. The checked value remains the original value. ```typescript expect(value1).to.equal(value2) ``` ```typescript expect(2).to.equal(2).to.equal(2) const obj = {} expect(obj).to.equal(obj) expect(2).equals(2) ``` -------------------------------- ### Check Constructor Calls with 'new' (TypeScript) Source: https://github.com/ranhs/soda-test/wiki/20-expect Verifies that a class constructor was called using the 'new' keyword. This assertion is applicable to spies or stubs created for class constructors. ```TypeScript expect(constructorSpy).to.have.been.calledWithNew expect(constructorStub).to.have.been.calledWithNew ``` ```TypeScript import { DerivedClass } from './class' ... @it('should call DerivedClass with new keyword') createDerviedClass( @spy('./class','DerviedClass') derivedclassSpy: SinonSpy): TR { const dc = new DerivedClass() expect(derivedclassSpy).to.have.been.calledWithNew expect(dc).to.be.instanceOf(DerivedClass) expect(derivedclassSpy).to.have.been.calledWithNew.calledOnce } ``` -------------------------------- ### Skip Constructor and Set Prototype Source: https://github.com/ranhs/soda-test/wiki/18-creatableclass Demonstrates creating a class instance without running its constructor by using an empty object cast and setting the prototype. ```ts const instnace: MyTestedClass = {} as never Object.setPrototypeOf(instance, MyTestedClass.prototype) ``` -------------------------------- ### Chai Expect to.not.have.property Source: https://github.com/ranhs/soda-test/wiki/20-expect Validates if an object does not have a specific property, or if it has the property but its value does not match the expected value. The checked value is the property's value with the 'not' flag. ```typescript expect(obj).to.not.have.property(name) expect(obj).to.not.have.property(name,value) ``` ```typescript expect({a:2,b:'#'}).to.not.have.property('c') expect({a:2,b:'#'}).to.not.have.property('c').to.equals('@') expect({a:2,b:'#'}).to.not.have.property('b','@') ``` -------------------------------- ### Spy on Console.log in Test Step Source: https://github.com/ranhs/soda-test/wiki/10-spies This example demonstrates how to spy on the `console.log` method within a test step using the `@spy` decorator. It verifies that `console.log` was called exactly once. ```ts @it('should spy on log') logSpy( @spy(console, 'log') console_log_spy: SinonSpy ): TR { foo() expect(console_log_spy.calledOnce).to.be.true expect(console_log_spy).to.have.been.calledOnce } ``` -------------------------------- ### Define Promise-returning Method Source: https://github.com/ranhs/soda-test/wiki/06-Asynchronous-test-step-with-Promise This TypeScript function, `addPromise`, takes two numbers and returns a Promise that resolves with their sum. Promises can also be rejected, though this example only shows resolution. ```typescript export function addPromise(a: number, b: number): Promise { return new Promise( (resolve,reject) => { resolve(a+b) }) } ``` -------------------------------- ### Configure Fixture with Component Outputs Source: https://github.com/ranhs/soda-test/wiki/25-integrationtest Explains how to set up a Soda Test fixture to test a component's outputs by specifying the output names in the fixture options. ```ts @fixture(TestComponent, {outputs: ['t1']}) fixture: SodaFixture ``` -------------------------------- ### API Testing with Soda-Test Test Cases Source: https://github.com/ranhs/soda-test/blob/main/README.md This section covers how to perform API testing using Soda Test's 'Test Cases' feature. It allows for structured and repeatable API validation. ```TypeScript // Example of API testing with test cases (specific code not provided in text, refer to wiki) ``` -------------------------------- ### Chai Expect to.deep.equal Source: https://github.com/ranhs/soda-test/wiki/20-expect Validates if two values are deeply equal, meaning their contents are the same recursively. This works for objects and arrays. The checked value remains the original value with the 'deep' flag. ```typescript expect(value1).to.deep.equal(value2) ``` ```typescript expect(2).to.deep.equal(2).to.equal(2) expect({a:2,b:'#'}).to.deep.equal({b:'#',a:2}).to.equal({a:2,b'#'}) ``` -------------------------------- ### Stub Getter with a Fixed Value Source: https://github.com/ranhs/soda-test/wiki/11-stubs This example demonstrates stubbing a getter method named 'Value' on 'BaseClass' from './lib'. The getter will always return the fixed value -1 when accessed via the stub. ```ts import { SinonStub } from 'sinon'; // Assuming './lib' exports BaseClass // Assuming BaseClass has a getter named 'Value' // @stub('./lib', 'BaseClass', 'Value').access(-1) // valueStub: SinonStub; ``` -------------------------------- ### TypeScript Configuration for Specs (tsconfig.spec.json) Source: https://github.com/ranhs/soda-test/wiki/03.1-getting-started-jest Defines TypeScript compiler options specifically for test files, extending the main `tsconfig.json` and including Jest and Node types. ```json { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": [ "jest", "node" ], "esModuleInterop": true, "emitDecoratorMetadata": true }, "files": [ "src/test.ts", "src/polyfills.ts" ], "include": [ "src/**/*.spec.ts", "src/**/*.d.ts" ] } ``` -------------------------------- ### Spy on External Library Method (lodash.isString) Source: https://github.com/ranhs/soda-test/wiki/10-spies This example shows how to spy on a method from an external library, like `isString` from lodash, by providing the library name and method name to the `@spy` decorator. ```ts @it("should spy external library as argument") checkSpy3(@spy('lodash', 'isString') spyIsString: SinonSpy): TR { let b = isString('AAA') expect(b).to.be.true expect(spyIsString).to.have.been.calledOnce } ``` -------------------------------- ### Update Main TypeScript Configuration (tsconfig.json) Source: https://github.com/ranhs/soda-test/wiki/03.1-getting-started-jest Updates the main `tsconfig.json` to ensure compatibility with Jest and Angular, adjusting target, module resolution, and library definitions. ```json { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "module": "esnext", "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "importHelpers": true, "target": "es2015", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2018", "dom" ] }, "angularCompilerOptions": { "fullTemplateTypeCheck": true, "strictInjectionParameters": true } } ```