Skip to content

Commit

Permalink
Merge pull request #2 from composable-com/feat/testing-2
Browse files Browse the repository at this point in the history
Additional unit tests
  • Loading branch information
dannytlake authored Sep 25, 2023
2 parents 4cbc299 + 30462b1 commit e990e81
Show file tree
Hide file tree
Showing 24 changed files with 560 additions and 135 deletions.
1 change: 1 addition & 0 deletions talonone-service/.prettierrc
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"singleQuote": true,
"parser": "typescript",
"printWidth": 80,
"arrowParens": "avoid",
"overrides": [
{
"files": "*.json",
Expand Down
3 changes: 2 additions & 1 deletion talonone-service/jest.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ module.exports = {
testMatch: ['**/tests/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[tj]s?(x)'],
preset: 'ts-jest',
testEnvironment: 'node',
};
setupFiles: ['<rootDir>/jest.setup.js']
}
9 changes: 9 additions & 0 deletions talonone-service/jest.setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const mockEnvironmentVariables = () => {
process.env.CTP_CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxx';
process.env.CTP_CLIENT_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
process.env.CTP_PROJECT_KEY = 'xxxxxxxxxxx';
process.env.CTP_SCOPE = 'xxxxxxxxxxx';
process.env.CTP_REGION = 'us-central1.gcp';
};

mockEnvironmentVariables();
11 changes: 3 additions & 8 deletions talonone-service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"create-ct-types": "ts-node src/scripts/create-ct-types.ts",
"test": "jest --config jest.config.cjs",
"test:local": "NODE_ENV=local jest --ci -i --setupFiles dotenv/config",
"test:coverage": "jest --config jest.config.cjs --coverage --collectCoverageFrom='src/**/*.{ts,jxs}'",
"test:coverage": "jest --config jest.config.cjs --coverage --collectCoverageFrom='src/**/*.{ts,jsx}'",
"connector:post-deploy": "node build/connector/post-deploy.js",
"connector:pre-undeploy": "node build/connector/pre-undeploy.js"
},
Expand All @@ -40,14 +40,9 @@
"zod": "^3.22.2"
},
"nodemonConfig": {
"watch": [
".env",
"src"
],
"watch": [".env", "src"],
"ext": "ts",
"ignore": [
"src/**/*.test.ts"
],
"ignore": ["src/**/*.test.ts"],
"exec": "DEBUG=App:* npx ts-node -r dotenv/config ./src/index"
},
"devDependencies": {
Expand Down
3 changes: 0 additions & 3 deletions talonone-service/src/@types/custom/params.d.ts

This file was deleted.

4 changes: 0 additions & 4 deletions talonone-service/src/@types/index.d.ts

This file was deleted.

36 changes: 36 additions & 0 deletions talonone-service/src/connector/post-deploy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { afterEach, describe, expect, it, jest } from '@jest/globals';
import { createType, createMyExtension } from './actions'
import { run } from './post-deploy'

jest.mock('./actions')

describe('Post-deploy', () => {
afterEach(() => {
jest.resetAllMocks()
jest.restoreAllMocks()
jest.resetModules()
})

it('should run start function', async () => {
(createMyExtension as jest.Mock).mockReturnValue({
data: 'success',
});

await run()
expect(createMyExtension).toHaveBeenCalled()
expect(createType).toHaveBeenCalled()
})

it('should handle errors', async () => {
const errorMessage = 'Something went wrong';
(createMyExtension as jest.Mock).mockImplementation(() => {
throw new Error(errorMessage);
});

const stderrSpy = jest.spyOn(process.stderr, 'write');
await run();

expect(stderrSpy).toHaveBeenCalledWith(`Post-deploy failed: Error: ${errorMessage}`);
expect(process.exitCode).toBe(1);
});
})
2 changes: 1 addition & 1 deletion talonone-service/src/connector/post-deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async function postDeploy(properties: Map<string, unknown>): Promise<void> {
await createType(apiRoot, lineItemMetadataType.key, lineItemMetadataType)
}

async function run(): Promise<void> {
export async function run(): Promise<void> {
try {
const properties = new Map(Object.entries(process.env))
await postDeploy(properties)
Expand Down
38 changes: 38 additions & 0 deletions talonone-service/src/connector/pre-undeploy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { afterEach, describe, expect, it, jest } from '@jest/globals';
import { deleteMyExtension } from './actions';
import { run } from './pre-undeploy';
import { createApiRoot } from '../services/commercetools/client/create.client'

jest.mock('./actions')
jest.mock('../services/commercetools/client/create.client')

describe('Pre-undeploy', () => {
afterEach(() => {
jest.resetAllMocks()
jest.restoreAllMocks()
jest.resetModules()
})

it('should run start function', async () => {
(deleteMyExtension as jest.Mock).mockReturnValue({
data: 'success',
});

await run()
expect(createApiRoot).toHaveBeenCalled()
expect(deleteMyExtension).toHaveBeenCalled()
})

it('should handle errors', async () => {
const errorMessage = 'Something went wrong';
(deleteMyExtension as jest.Mock).mockImplementation(() => {
throw new Error(errorMessage);
});

const stderrSpy = jest.spyOn(process.stderr, 'write');
await run();

expect(stderrSpy).toHaveBeenCalledWith(`Pre-undeploy failed: Error: ${errorMessage}`);
expect(process.exitCode).toBe(1);
});
})
2 changes: 1 addition & 1 deletion talonone-service/src/connector/pre-undeploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ async function preUndeploy(): Promise<void> {
await deleteMyExtension(apiRoot)
}

async function run(): Promise<void> {
export async function run(): Promise<void> {
try {
await preUndeploy()
} catch (error) {
Expand Down
45 changes: 45 additions & 0 deletions talonone-service/src/handlers/actions/cart-actions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { Effect } from 'talon_one'
import { Cart } from '@commercetools/platform-sdk'
import { EffectHandlers } from '../effects/types'
import { getCartActions } from './cart-actions'

describe('getCartActions', () => {
beforeEach(() => {
jest.resetAllMocks()
jest.restoreAllMocks()
})
it('should return empty array if no effects are given', () => {
const mockCart = {} as unknown as Cart
const mockEffects = [] as unknown as Effect[]
const mockHandlers = {
someEffectType: jest.fn().mockReturnValue('someActionResult')
}

const result = getCartActions(mockCart, mockEffects, mockHandlers)
expect(result).toEqual([])
})

it('should return the correct cart actions based on given effects and handlers', () => {
const mockCart = {} as unknown as Cart

const mockEffects = [
{ effectType: 'someEffectType', props: { key: 'value' } },
{ effectType: 'unhandledEffectType', props: { key2: 'value2' } }
] as unknown as Effect[]

const mockHandlers = {
someEffectType: jest.fn().mockReturnValue('someActionResult')
}

const result = getCartActions(mockCart, mockEffects, mockHandlers)

// Assert that the handler for 'someEffectType' was called with correct properties
expect(mockHandlers.someEffectType).toHaveBeenCalledWith({
key: 'value',
cart: mockCart
})

// Assert the expected result
expect(result).toEqual(['someActionResult'])
})
})
57 changes: 57 additions & 0 deletions talonone-service/src/handlers/actions/order-actions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Effect } from 'talon_one'
import { Order } from '@commercetools/platform-sdk'
import { getOrderActions } from './order-actions'

describe('getCartActions', () => {
beforeEach(() => {
jest.resetAllMocks()
jest.restoreAllMocks()
})

it('should return an empty array if no effects are provided', async () => {
const mockOrder = {
anonymousId: null
} as unknown as Order

const result = await getOrderActions(mockOrder, [], {})
expect(result).toEqual([])
})

it('should return an empty array if order has an anonymousId', async () => {
const mockOrder = {
anonymousId: 'someId'
} as unknown as Order

const mockEffects = [
{ effectType: 'someEffectType', props: { key: 'value' } }
] as unknown as Effect[]

const result = await getOrderActions(mockOrder, mockEffects, {})
expect(result).toEqual([])
})

it('should return the correct order actions based on given effects and handlers', async () => {
const mockOrder = {
anonymousId: null
} as unknown as Order

const mockEffects = [
{ effectType: 'someEffectType', props: { key: 'value' } },
{ effectType: 'unhandledEffectType', props: { key2: 'value2' } }
] as unknown as Effect[]

const mockHandlerResult = 'someActionResult'
const mockHandlers = {
someEffectType: jest.fn().mockResolvedValue(mockHandlerResult)
}

const result = await getOrderActions(mockOrder, mockEffects, mockHandlers)

expect(mockHandlers.someEffectType).toHaveBeenCalledWith({
key: 'value',
order: mockOrder
})

expect(result).toEqual([mockHandlerResult])
})
})
11 changes: 8 additions & 3 deletions talonone-service/src/handlers/effects/cart/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { describe, expect, test, jest } from '@jest/globals';
import { EffectHandlers } from '../types'
import getCartEffectHandlers from './index'
import getDiscountApplied from './setDiscount'

jest.mock('./setDiscount')

describe('getCartEffectHandlers', () => {
let currencyCode: string
Expand All @@ -16,13 +20,14 @@ describe('getCartEffectHandlers', () => {
})

it('should return an object with the setDiscount effect handler', () => {
(getDiscountApplied as jest.Mock).mockReturnValue(null)

const effectHandlers: EffectHandlers = getCartEffectHandlers(
currencyCode,
taxCategoryId
)

expect(effectHandlers).toEqual({
setDiscount: expect.any(Function)
})
expect(effectHandlers).toHaveProperty('setDiscount')
expect(effectHandlers.setDiscount({})).toBeNull()
})
})
27 changes: 27 additions & 0 deletions talonone-service/src/handlers/effects/order/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { describe, expect, jest } from '@jest/globals';
import { EffectHandlers } from '../types';
import addLoyaltyPointsHandler from './addLoyaltyPoints';
import getOrderEffectHandlers from './index';
import rollbackAddedLoyaltyPointsHandler from './rollbackAddedLoyaltyPoints';

jest.mock('./addLoyaltyPoints')
jest.mock('./rollbackAddedLoyaltyPoints')

describe('getOrderEffectHandlers', () => {
afterEach(() => {
jest.restoreAllMocks()
jest.resetAllMocks()
})

it('should return an object with the addLoyaltyPoints and rollbackAddedLoyaltyPoints effect handlers', () => {
(addLoyaltyPointsHandler as jest.Mock).mockReturnValue(null);
(rollbackAddedLoyaltyPointsHandler as jest.Mock).mockReturnValue(null);

const effectHandlers: EffectHandlers = getOrderEffectHandlers()

expect(effectHandlers).toHaveProperty('addLoyaltyPoints')
expect(effectHandlers).toHaveProperty('rollbackAddedLoyaltyPoints')
expect(effectHandlers.addLoyaltyPoints({})).toBeNull()
expect(effectHandlers.rollbackAddedLoyaltyPoints({})).toBeNull()
})
})
Loading

0 comments on commit e990e81

Please sign in to comment.