chore: Use module test runner in all modules (#6706)

I replaced the custom test setup with the test runner. This should make migrating to mikroorm 6 a lot easier once we do it.

There are few more modules to be done, but I thought the PR is super big already so we can tackle them separately.

Note that there are no or very little test changes, it is mostly the setup around the tests.
This commit is contained in:
Stevche Radevski authored and GitHub committed 2024-03-14 21:01:50 +00:00
1 parent 1eb90f739b
commit 68d869607f
102 files changed
+959 -4740

No files matched your search

@@ -1,35 +1,19 @@
import { AuthUserService } from "@services"
import ContainerLoader from "../../../../src/loaders/container"
import { MikroOrmWrapper } from "../../../utils"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { asValue } from "awilix"
import { createAuthUsers } from "../../../__fixtures__/auth-user"
import { createMedusaContainer } from "@medusajs/utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { Modules } from "@medusajs/modules-sdk"
import { IAuthModuleService } from "@medusajs/types"
jest.setTimeout(30000)
describe("AuthUser Service", () => {
let service: AuthUserService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
moduleIntegrationTestRunner({
moduleName: Modules.AUTH,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IAuthModuleService>) => {
describe("AuthUser Service", () => {
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
testManager = await MikroOrmWrapper.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("authUserService")
await createAuthUsers(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
await createAuthUsers(MikroOrmWrapper.forkManager())
})
describe("list", () => {
@@ -242,4 +226,6 @@ describe("AuthUser Service", () => {
)
})
})
})
},
})
@@ -1,41 +1,19 @@
import { IAuthModuleService } from "@medusajs/types"
import { MikroOrmWrapper } from "../../../utils"
import { Modules } from "@medusajs/modules-sdk"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { createAuthUsers } from "../../../__fixtures__/auth-user"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { initModules } from "medusa-test-utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
describe("AuthModuleService - AuthUser", () => {
let service: IAuthModuleService
let testManager: SqlEntityManager
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.AUTH]
shutdownFunc = shutdown
})
moduleIntegrationTestRunner({
moduleName: Modules.AUTH,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IAuthModuleService>) => {
describe("AuthModuleService - AuthUser", () => {
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
testManager = MikroOrmWrapper.forkManager()
await createAuthUsers(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
afterAll(async () => {
await shutdownFunc()
await createAuthUsers(MikroOrmWrapper.forkManager())
})
describe("listAuthUsers", () => {
@@ -254,4 +232,6 @@ describe("AuthModuleService - AuthUser", () => {
)
})
})
})
},
})
@@ -1,46 +1,17 @@
import { MedusaModule, Modules } from "@medusajs/modules-sdk"
import { IAuthModuleService } from "@medusajs/types"
import { MikroOrmWrapper } from "../../../utils"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { initModules } from "medusa-test-utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
describe("AuthModuleService - AuthProvider", () => {
let service: IAuthModuleService
let testManager: SqlEntityManager
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.AUTH]
shutdownFunc = shutdown
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
testManager = MikroOrmWrapper.forkManager()
if (service.__hooks?.onApplicationStart) {
await service.__hooks.onApplicationStart()
}
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
MedusaModule.clearInstances()
})
afterAll(async () => {
await shutdownFunc()
})
moduleIntegrationTestRunner({
moduleName: Modules.AUTH,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IAuthModuleService>) => {
describe("AuthModuleService - AuthProvider", () => {
describe("authenticate", () => {
it("authenticate validates that a provider is registered in container", async () => {
const { success, error } = await service.authenticate(
@@ -65,4 +36,6 @@ describe("AuthModuleService - AuthProvider", () => {
)
})
})
})
},
})
@@ -1,51 +1,33 @@
import { MedusaModule, Modules } from "@medusajs/modules-sdk"
import { IAuthModuleService } from "@medusajs/types"
import { MikroOrmWrapper } from "../../../utils"
import Scrypt from "scrypt-kdf"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { createAuthUsers } from "../../../__fixtures__/auth-user"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { initModules } from "medusa-test-utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
const seedDefaultData = async (testManager) => {
await createAuthUsers(testManager)
const seedDefaultData = async (manager) => {
await createAuthUsers(manager)
}
describe("AuthModuleService - AuthProvider", () => {
let service: IAuthModuleService
let testManager: SqlEntityManager
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.AUTH]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
testManager = MikroOrmWrapper.forkManager()
if (service.__hooks?.onApplicationStart) {
await service.__hooks.onApplicationStart()
}
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
MedusaModule.clearInstances()
})
moduleIntegrationTestRunner({
moduleName: Modules.AUTH,
moduleOptions: {
providers: [
{
name: "emailpass",
scopes: {
admin: {},
store: {},
},
},
],
},
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IAuthModuleService>) => {
describe("AuthModuleService - AuthProvider", () => {
describe("authenticate", () => {
it("authenticate validates that a provider is registered in container", async () => {
const password = "supersecret"
@@ -54,8 +36,8 @@ describe("AuthModuleService - AuthProvider", () => {
await Scrypt.kdf(password, { logN: 15, r: 8, p: 1 })
).toString("base64")
await seedDefaultData(testManager)
await createAuthUsers(testManager, [
await seedDefaultData(MikroOrmWrapper.forkManager())
await createAuthUsers(MikroOrmWrapper.forkManager(), [
// Add authenticated user
{
provider: "emailpass",
@@ -85,7 +67,7 @@ describe("AuthModuleService - AuthProvider", () => {
})
it("fails when no password is given", async () => {
await seedDefaultData(testManager)
await seedDefaultData(MikroOrmWrapper.forkManager())
const res = await service.authenticate("emailpass", {
body: { email: "test@test.com" },
@@ -99,7 +81,7 @@ describe("AuthModuleService - AuthProvider", () => {
})
it("fails when no email is given", async () => {
await seedDefaultData(testManager)
await seedDefaultData(MikroOrmWrapper.forkManager())
const res = await service.authenticate("emailpass", {
body: { password: "supersecret" },
@@ -119,8 +101,8 @@ describe("AuthModuleService - AuthProvider", () => {
await Scrypt.kdf(password, { logN: 15, r: 8, p: 1 })
).toString("base64")
await seedDefaultData(testManager)
await createAuthUsers(testManager, [
await seedDefaultData(MikroOrmWrapper.forkManager())
await createAuthUsers(MikroOrmWrapper.forkManager(), [
// Add authenticated user
{
provider: "emailpass",
@@ -146,4 +128,6 @@ describe("AuthModuleService - AuthProvider", () => {
})
})
})
})
},
})
@@ -1,6 +0,0 @@
if (typeof process.env.DB_TEMP_NAME === "undefined") {
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
process.env.DB_TEMP_NAME = `medusa-auth-integration-${tempName}`
}
process.env.MEDUSA_AUTH_DB_SCHEMA = "public"
-3
View File
@@ -1,3 +0,0 @@
import { JestUtils } from "medusa-test-utils"
JestUtils.afterAllHookDropDatabase()
@@ -1,6 +0,0 @@
import { ModuleServiceInitializeOptions } from "@medusajs/types"
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
schema: "public",
clientUrl: "medusa-auth-test",
}
@@ -1,18 +0,0 @@
import * as AuthModels from "@models"
import { TestDatabaseUtils } from "medusa-test-utils"
const pathToMigrations = "../../src/migrations"
const mikroOrmEntities = AuthModels as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper({
mikroOrmEntities,
pathToMigrations,
})
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig({
mikroOrmEntities,
pathToMigrations,
})
export const DB_URL = TestDatabaseUtils.getDatabaseURL()
@@ -1,42 +0,0 @@
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
import { DB_URL } from "./database"
export function getInitModuleConfig() {
const moduleOptions = {
defaultAdapterOptions: {
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_AUTH_DB_SCHEMA,
},
},
providers: [
{
name: "emailpass",
scopes: {
admin: {},
store: {},
},
},
],
}
const injectedDependencies = {}
const modulesConfig_ = {
[Modules.AUTH]: {
definition: ModulesDefinition[Modules.AUTH],
options: moduleOptions,
},
}
return {
injectedDependencies,
modulesConfig: modulesConfig_,
databaseConfig: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_AUTH_DB_SCHEMA,
},
joinerConfig: [],
}
}
@@ -1,2 +0,0 @@
export * from "./config"
export * from "./database"
-2
View File
@@ -18,6 +18,4 @@ module.exports = {
testEnvironment: `node`,
moduleFileExtensions: [`js`, `ts`],
modulePathIgnorePatterns: ["dist/"],
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
}
@@ -1,38 +1,17 @@
import { Modules } from "@medusajs/modules-sdk"
import { ICartModuleService } from "@medusajs/types"
import { CheckConstraintViolationException } from "@mikro-orm/core"
import { initModules } from "medusa-test-utils"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(50000)
describe("Cart Module Service", () => {
let service: ICartModuleService
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.CART]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
moduleIntegrationTestRunner({
moduleName: Modules.CART,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<ICartModuleService>) => {
describe("Cart Module Service", () => {
describe("create", () => {
it("should throw an error when required params are not passed", async () => {
const error = await service
@@ -231,7 +210,9 @@ describe("Cart Module Service", () => {
])
.catch((e) => e)
expect(error.message).toContain('Cart with id "none-existing" not found')
expect(error.message).toContain(
'Cart with id "none-existing" not found'
)
})
it("should update a cart successfully", async () => {
@@ -881,7 +862,9 @@ describe("Cart Module Service", () => {
},
])
const adjustments = await service.setLineItemAdjustments(createdCart.id, [
const adjustments = await service.setLineItemAdjustments(
createdCart.id,
[
{
item_id: itemOne.id,
amount: 100,
@@ -892,7 +875,8 @@ describe("Cart Module Service", () => {
amount: 200,
code: "FREE-2",
},
])
]
)
expect(adjustments).toEqual(
expect.arrayContaining([
@@ -925,13 +909,16 @@ describe("Cart Module Service", () => {
},
])
const adjustments = await service.setLineItemAdjustments(createdCart.id, [
const adjustments = await service.setLineItemAdjustments(
createdCart.id,
[
{
item_id: itemOne.id,
amount: 100,
code: "FREE",
},
])
]
)
expect(adjustments).toEqual(
expect.arrayContaining([
@@ -989,13 +976,16 @@ describe("Cart Module Service", () => {
},
])
const adjustments = await service.setLineItemAdjustments(createdCart.id, [
const adjustments = await service.setLineItemAdjustments(
createdCart.id,
[
{
item_id: itemOne.id,
amount: 100,
code: "FREE",
},
])
]
)
expect(adjustments).toEqual(
expect.arrayContaining([
@@ -1041,13 +1031,16 @@ describe("Cart Module Service", () => {
},
])
const adjustments = await service.setLineItemAdjustments(createdCart.id, [
const adjustments = await service.setLineItemAdjustments(
createdCart.id,
[
{
item_id: itemOne.id,
amount: 100,
code: "FREE",
},
])
]
)
expect(adjustments).toEqual(
expect.arrayContaining([
@@ -1109,13 +1102,16 @@ describe("Cart Module Service", () => {
},
])
const adjustments = await service.addLineItemAdjustments(createdCart.id, [
const adjustments = await service.addLineItemAdjustments(
createdCart.id,
[
{
item_id: itemOne.id,
amount: 100,
code: "FREE",
},
])
]
)
expect(adjustments).toEqual(
expect.arrayContaining([
@@ -1150,7 +1146,9 @@ describe("Cart Module Service", () => {
},
])
const adjustments = await service.addLineItemAdjustments(createdCart.id, [
const adjustments = await service.addLineItemAdjustments(
createdCart.id,
[
{
item_id: itemOne.id,
amount: 100,
@@ -1161,7 +1159,8 @@ describe("Cart Module Service", () => {
amount: 150,
code: "CODE-2",
},
])
]
)
expect(adjustments).toEqual(
expect.arrayContaining([
@@ -1665,18 +1664,24 @@ describe("Cart Module Service", () => {
},
])
const [shippingMethodOne] = await service.addShippingMethods(cartOne.id, [
const [shippingMethodOne] = await service.addShippingMethods(
cartOne.id,
[
{
amount: 100,
name: "test",
},
])
const [shippingMethodTwo] = await service.addShippingMethods(cartTwo.id, [
]
)
const [shippingMethodTwo] = await service.addShippingMethods(
cartTwo.id,
[
{
amount: 200,
name: "test-2",
},
])
]
)
await service.addShippingMethodAdjustments([
// item from cart one
@@ -1744,12 +1749,15 @@ describe("Cart Module Service", () => {
},
])
const [shippingMethodOne] = await service.addShippingMethods(cartOne.id, [
const [shippingMethodOne] = await service.addShippingMethods(
cartOne.id,
[
{
amount: 100,
name: "test",
},
])
]
)
const error = await service
.addShippingMethodAdjustments(cartTwo.id, [
@@ -2332,4 +2340,6 @@ describe("Cart Module Service", () => {
expect(taxLines?.length).toBe(0)
})
})
})
},
})
@@ -1,6 +0,0 @@
if (typeof process.env.DB_TEMP_NAME === "undefined") {
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
process.env.DB_TEMP_NAME = `medusa-cart-integration-${tempName}`
}
process.env.MEDUSA_CART_DB_SCHEMA = "public"
-3
View File
@@ -1,3 +0,0 @@
import { JestUtils } from "medusa-test-utils"
JestUtils.afterAllHookDropDatabase()
@@ -1,6 +0,0 @@
import { ModuleServiceInitializeOptions } from "@medusajs/types"
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
schema: "public",
clientUrl: "medusa-cart-test",
}
@@ -1,18 +0,0 @@
import { TestDatabaseUtils } from "medusa-test-utils"
import * as CartModels from "@models"
const pathToMigrations = "../../src/migrations"
const mikroOrmEntities = CartModels as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper({
mikroOrmEntities,
pathToMigrations,
})
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig({
mikroOrmEntities,
pathToMigrations,
})
export const DB_URL = TestDatabaseUtils.getDatabaseURL()
@@ -1,33 +0,0 @@
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
import { DB_URL } from "./database"
export function getInitModuleConfig() {
const moduleOptions = {
defaultAdapterOptions: {
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_CART_DB_SCHEMA,
},
},
}
const injectedDependencies = {}
const modulesConfig_ = {
[Modules.CART]: {
definition: ModulesDefinition[Modules.CART],
options: moduleOptions,
},
}
return {
injectedDependencies,
modulesConfig: modulesConfig_,
databaseConfig: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_CART_DB_SCHEMA,
},
joinerConfig: [],
}
}
@@ -1,2 +0,0 @@
export * from "./config"
export * from "./database"
-2
View File
@@ -18,6 +18,4 @@ module.exports = {
testEnvironment: `node`,
moduleFileExtensions: [`js`, `ts`],
modulePathIgnorePatterns: ["dist/"],
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
}
@@ -1,37 +1,16 @@
import { ICustomerModuleService } from "@medusajs/types"
import { MikroOrmWrapper } from "../../../utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { Modules } from "@medusajs/modules-sdk"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { initModules } from "medusa-test-utils"
jest.setTimeout(30000)
describe("Customer Module Service", () => {
let service: ICustomerModuleService
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.CUSTOMER]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
moduleIntegrationTestRunner({
moduleName: Modules.CUSTOMER,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<ICustomerModuleService>) => {
describe("Customer Module Service", () => {
describe("create", () => {
it("should create a single customer", async () => {
const customerData = {
@@ -231,7 +210,11 @@ describe("Customer Module Service", () => {
describe("list", () => {
it("should list all customers when no filters are applied", async () => {
await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
{
first_name: "Jane",
last_name: "Smith",
@@ -289,7 +272,11 @@ describe("Customer Module Service", () => {
const vipGroup = await service.createCustomerGroup({ name: "VIP" })
const [john] = await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
{
first_name: "Jane",
last_name: "Smith",
@@ -329,7 +316,11 @@ describe("Customer Module Service", () => {
describe("addCustomerToGroup", () => {
it("should add a single customer to a customer group", async () => {
const [customer] = await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
])
const [group] = await service.createCustomerGroup([{ name: "VIP" }])
@@ -353,7 +344,11 @@ describe("Customer Module Service", () => {
it("should add multiple customers to customer groups", async () => {
const customers = await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
{
first_name: "Jane",
last_name: "Smith",
@@ -395,7 +390,11 @@ describe("Customer Module Service", () => {
describe("update", () => {
it("should update a single customer", async () => {
const [customer] = await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
])
const updateData = { first_name: "Jonathan" }
@@ -408,7 +407,11 @@ describe("Customer Module Service", () => {
it("should update multiple customers by IDs", async () => {
const customers = await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
{
first_name: "Jane",
last_name: "Smith",
@@ -429,8 +432,16 @@ describe("Customer Module Service", () => {
it("should update customers using a selector", async () => {
await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{ first_name: "Jane", last_name: "Doe", email: "jane.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
{
first_name: "Jane",
last_name: "Doe",
email: "jane.doe@example.com",
},
])
const selector = { last_name: "Doe" }
@@ -448,7 +459,11 @@ describe("Customer Module Service", () => {
describe("delete", () => {
it("should delete a single customer", async () => {
const [customer] = await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
])
await service.delete(customer.id)
@@ -460,7 +475,11 @@ describe("Customer Module Service", () => {
it("should delete multiple customers by IDs", async () => {
const customers = await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
{
first_name: "Jane",
last_name: "Smith",
@@ -480,8 +499,16 @@ describe("Customer Module Service", () => {
it("should delete customers using a selector", async () => {
await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{ first_name: "Jane", last_name: "Doe", email: "jane.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
{
first_name: "Jane",
last_name: "Doe",
email: "jane.doe@example.com",
},
])
const selector = { last_name: "Doe" }
@@ -550,7 +577,9 @@ describe("Customer Module Service", () => {
await expect(
service.retrieveCustomerGroup(group.id)
).rejects.toThrowError(`CustomerGroup with id: ${group.id} was not found`)
).rejects.toThrowError(
`CustomerGroup with id: ${group.id} was not found`
)
})
it("should delete multiple customer groups by IDs", async () => {
@@ -572,12 +601,17 @@ describe("Customer Module Service", () => {
})
it("should delete customer groups using a selector", async () => {
await service.createCustomerGroup([{ name: "VIP" }, { name: "Regular" }])
await service.createCustomerGroup([
{ name: "VIP" },
{ name: "Regular" },
])
const selector = { name: "VIP" }
await service.deleteCustomerGroups(selector)
const remainingGroups = await service.listCustomerGroups({ name: "VIP" })
const remainingGroups = await service.listCustomerGroups({
name: "VIP",
})
expect(remainingGroups.length).toBe(0)
})
@@ -914,7 +948,11 @@ describe("Customer Module Service", () => {
it("should remove a single customer from a group", async () => {
// Creating a customer and a group
const [customer] = await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
])
const [group] = await service.createCustomerGroup([{ name: "VIP" }])
@@ -948,7 +986,11 @@ describe("Customer Module Service", () => {
it("should remove multiple customers from groups", async () => {
// Creating multiple customers and groups
const customers = await service.create([
{ first_name: "John", last_name: "Doe", email: "john.doe@example.com" },
{
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
},
{
first_name: "Jane",
last_name: "Smith",
@@ -1154,4 +1196,6 @@ describe("Customer Module Service", () => {
expect(restoredGroups.length).toBe(2)
})
})
})
},
})
@@ -1,6 +0,0 @@
if (typeof process.env.DB_TEMP_NAME === "undefined") {
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
process.env.DB_TEMP_NAME = `medusa-customer-integration-${tempName}`
}
process.env.MEDUSA_CUSTOMER_DB_SCHEMA = "public"
@@ -1,3 +0,0 @@
import { JestUtils } from "medusa-test-utils"
JestUtils.afterAllHookDropDatabase()
@@ -1,6 +0,0 @@
import { ModuleServiceInitializeOptions } from "@medusajs/types"
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
schema: "public",
clientUrl: "medusa-customer-test",
}
@@ -1,18 +0,0 @@
import { TestDatabaseUtils } from "medusa-test-utils"
import * as Models from "@models"
const pathToMigrations = "../../src/migrations"
const mikroOrmEntities = Models as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper({
mikroOrmEntities,
pathToMigrations,
})
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig({
mikroOrmEntities,
pathToMigrations,
})
export const DB_URL = TestDatabaseUtils.getDatabaseURL()
@@ -1,33 +0,0 @@
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
import { DB_URL } from "./database"
export function getInitModuleConfig() {
const moduleOptions = {
defaultAdapterOptions: {
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_CUSTOMER_DB_SCHEMA,
},
},
}
const injectedDependencies = {}
const modulesConfig_ = {
[Modules.CUSTOMER]: {
definition: ModulesDefinition[Modules.CUSTOMER],
options: moduleOptions,
},
}
return {
injectedDependencies,
modulesConfig: modulesConfig_,
databaseConfig: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_CUSTOMER_DB_SCHEMA,
},
joinerConfig: [],
}
}
@@ -1,2 +0,0 @@
export * from "./config"
export * from "./database"
-2
View File
@@ -16,6 +16,4 @@ module.exports = {
testEnvironment: `node`,
moduleFileExtensions: [`js`, `ts`],
modulePathIgnorePatterns: ["dist/"],
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
}
@@ -1,353 +0,0 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { MoneyAmount } from "@models"
import { MoneyAmountService } from "@services"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
import { createMoneyAmounts } from "../../../__fixtures__/money-amount"
import { MikroOrmWrapper } from "../../../utils"
jest.setTimeout(30000)
describe("MoneyAmount Service", () => {
let service: MoneyAmountService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let data!: MoneyAmount[]
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("moneyAmountService")
testManager = await MikroOrmWrapper.forkManager()
data = await createMoneyAmounts(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("should list all moneyAmounts", async () => {
const moneyAmountsResult = await service.list()
expect(JSON.parse(JSON.stringify(moneyAmountsResult))).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: "money-amount-USD",
amount: 500,
}),
expect.objectContaining({
id: "money-amount-EUR",
amount: 400,
}),
expect.objectContaining({
id: "money-amount-CAD",
amount: 600,
}),
])
)
})
it("should list moneyAmounts by id", async () => {
const moneyAmountsResult = await service.list({
id: ["money-amount-USD"],
})
expect(JSON.parse(JSON.stringify(moneyAmountsResult))).toEqual([
expect.objectContaining({
id: "money-amount-USD",
}),
])
})
it("should list moneyAmounts with relations and selects", async () => {
const moneyAmountsResult = await service.list(
{
id: ["money-amount-USD"],
},
{
select: ["id", "min_quantity", "currency_code", "amount"],
}
)
const serialized = JSON.parse(JSON.stringify(moneyAmountsResult))
expect(serialized).toEqual([
{
id: "money-amount-USD",
amount: 500,
min_quantity: "1",
currency_code: "USD",
},
])
})
it("should list moneyAmounts scoped by currency_code", async () => {
const moneyAmountsResult = await service.list(
{
currency_code: ["USD"],
},
{
select: ["id", "min_quantity", "currency_code", "amount"],
}
)
const serialized = JSON.parse(JSON.stringify(moneyAmountsResult))
expect(serialized).toEqual([
{
id: "money-amount-USD",
min_quantity: "1",
currency_code: "USD",
amount: 500,
},
])
})
})
describe("listAndCount", () => {
it("should return moneyAmounts and count", async () => {
const [moneyAmountsResult, count] = await service.listAndCount()
expect(count).toEqual(3)
expect(JSON.parse(JSON.stringify(moneyAmountsResult))).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: "money-amount-USD",
}),
expect.objectContaining({
id: "money-amount-EUR",
}),
expect.objectContaining({
id: "money-amount-CAD",
}),
])
)
})
it("should return moneyAmounts and count when filtered", async () => {
const [moneyAmountsResult, count] = await service.listAndCount({
id: ["money-amount-USD"],
})
expect(count).toEqual(1)
expect(moneyAmountsResult).toEqual([
expect.objectContaining({
id: "money-amount-USD",
}),
])
})
it("list moneyAmounts with relations and selects", async () => {
const [moneyAmountsResult, count] = await service.listAndCount(
{
id: ["money-amount-USD"],
},
{
select: ["id", "min_quantity", "currency_code", "amount"],
}
)
const serialized = JSON.parse(JSON.stringify(moneyAmountsResult))
expect(count).toEqual(1)
expect(serialized).toEqual([
{
id: "money-amount-USD",
amount: 500,
min_quantity: "1",
currency_code: "USD",
},
])
})
it("should return moneyAmounts and count when using skip and take", async () => {
const [moneyAmountsResult, count] = await service.listAndCount(
{},
{ skip: 1, take: 1 }
)
expect(count).toEqual(3)
expect(moneyAmountsResult).toEqual([
expect.objectContaining({
id: "money-amount-EUR",
}),
])
})
it("should return requested fields", async () => {
const [moneyAmountsResult, count] = await service.listAndCount(
{},
{
take: 1,
select: ["id", "amount"],
}
)
const serialized = JSON.parse(JSON.stringify(moneyAmountsResult))
expect(count).toEqual(3)
expect(serialized).toEqual([
{
id: "money-amount-CAD",
amount: 600,
},
])
})
})
describe("retrieve", () => {
const id = "money-amount-USD"
const amount = 500
it("should return moneyAmount for the given id", async () => {
const moneyAmount = await service.retrieve(id)
expect(moneyAmount).toEqual(
expect.objectContaining({
id,
})
)
})
it("should throw an error when moneyAmount with id does not exist", async () => {
let error
try {
await service.retrieve("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"MoneyAmount with id: does-not-exist was not found"
)
})
it("should throw an error when a id is not provided", async () => {
let error
try {
await service.retrieve(undefined as unknown as string)
} catch (e) {
error = e
}
expect(error.message).toEqual("moneyAmount - id must be defined")
})
it("should return moneyAmount based on config select param", async () => {
const moneyAmount = await service.retrieve(id, {
select: ["id", "amount"],
})
const serialized = JSON.parse(JSON.stringify(moneyAmount))
expect(serialized).toEqual({
id,
amount,
})
})
})
describe("delete", () => {
const id = "money-amount-USD"
it("should delete the moneyAmounts given an id successfully", async () => {
await service.delete([id])
const moneyAmounts = await service.list({
id: [id],
})
expect(moneyAmounts).toHaveLength(0)
})
})
describe("update", () => {
const id = "money-amount-USD"
it("should update the amount of the moneyAmount successfully", async () => {
await service.update([
{
id,
amount: 700,
},
])
const moneyAmount = JSON.parse(JSON.stringify(await service.retrieve(id)))
expect(moneyAmount.amount).toEqual(700)
})
it("should update the currency of the moneyAmount successfully", async () => {
await service.update([
{
id,
currency_code: "EUR",
},
])
const moneyAmount = await service.retrieve(id)
expect(moneyAmount.currency_code).toEqual("EUR")
})
it("should throw an error when a id does not exist", async () => {
let error
try {
await service.update([
{
id: "does-not-exist",
amount: 666,
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
'MoneyAmount with id "does-not-exist" not found'
)
})
})
describe("create", () => {
it("should create a moneyAmount successfully", async () => {
await service.create([
{
id: "money-amount-TESM",
currency_code: "USD",
amount: 333,
min_quantity: 1,
max_quantity: 4,
},
])
const [moneyAmount] = await service.list({
id: ["money-amount-TESM"],
})
expect(JSON.parse(JSON.stringify(moneyAmount))).toEqual(
expect.objectContaining({
id: "money-amount-TESM",
currency_code: "USD",
amount: 333,
min_quantity: "1",
max_quantity: "4",
})
)
})
})
})
@@ -1,243 +0,0 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { PriceListRuleService } from "@services"
import { createPriceLists } from "../../../__fixtures__/price-list"
import { createPriceListRules } from "../../../__fixtures__/price-list-rules"
import { createRuleTypes } from "../../../__fixtures__/rule-type"
import { MikroOrmWrapper } from "../../../utils"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
jest.setTimeout(30000)
describe("PriceListRule Service", () => {
let service: PriceListRuleService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("priceListRuleService")
testManager = await MikroOrmWrapper.forkManager()
await createRuleTypes(testManager)
await createPriceLists(testManager)
await createPriceListRules(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("should list all priceListRules", async () => {
const priceListRuleResult = await service.list()
expect(priceListRuleResult).toEqual([
expect.objectContaining({
id: "price-list-rule-1",
}),
expect.objectContaining({
id: "price-list-rule-2",
}),
])
})
it("should list priceListRules scoped by priceListRule id", async () => {
const priceListRuleResult = await service.list({
id: ["price-list-rule-1"],
})
expect(priceListRuleResult).toEqual([
expect.objectContaining({
id: "price-list-rule-1",
}),
])
})
})
describe("listAndCount", () => {
it("should return pricelistrules and count", async () => {
const [priceListRuleResult, count] = await service.listAndCount()
expect(count).toEqual(2)
expect(priceListRuleResult).toEqual([
expect.objectContaining({
id: "price-list-rule-1",
}),
expect.objectContaining({
id: "price-list-rule-2",
}),
])
})
it("should return pricelistrules and count when filtered", async () => {
const [priceListRuleResult, count] = await service.listAndCount({
id: ["price-list-rule-1"],
})
expect(count).toEqual(1)
expect(priceListRuleResult).toEqual([
expect.objectContaining({
id: "price-list-rule-1",
}),
])
})
it("should return pricelistrules and count when using skip and take", async () => {
const [priceListRuleResult, count] = await service.listAndCount(
{},
{ skip: 1, take: 1 }
)
expect(count).toEqual(2)
expect(priceListRuleResult).toEqual([
expect.objectContaining({
id: "price-list-rule-2",
}),
])
})
it("should return requested fields", async () => {
const [priceListRuleResult, count] = await service.listAndCount(
{},
{
take: 1,
select: ["id"],
}
)
const serialized = JSON.parse(JSON.stringify(priceListRuleResult))
expect(count).toEqual(2)
expect(serialized).toEqual([
{
id: "price-list-rule-1",
},
])
})
})
describe("retrieve", () => {
const id = "price-list-rule-1"
it("should return priceList for the given id", async () => {
const priceListRuleResult = await service.retrieve(id)
expect(priceListRuleResult).toEqual(
expect.objectContaining({
id,
})
)
})
it("should throw an error when priceListRule with id does not exist", async () => {
let error
try {
await service.retrieve("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"PriceListRule with id: does-not-exist was not found"
)
})
it("should throw an error when a id is not provided", async () => {
let error
try {
await service.retrieve(undefined as unknown as string)
} catch (e) {
error = e
}
expect(error.message).toEqual("priceListRule - id must be defined")
})
})
describe("delete", () => {
const id = "price-list-rule-1"
it("should delete the pricelists given an id successfully", async () => {
await service.delete([id])
const priceListResult = await service.list({
id: [id],
})
expect(priceListResult).toHaveLength(0)
})
})
describe("update", () => {
const id = "price-list-rule-2"
it("should update the value of the priceListRule successfully", async () => {
await service.update([
{
id,
price_list_id: "price-list-1",
},
])
const priceList = await service.retrieve(id, {
relations: ["price_list"],
})
expect(priceList.price_list.id).toEqual("price-list-1")
})
it("should throw an error when a id does not exist", async () => {
let error
try {
await service.update([
{
id: "does-not-exist",
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
'PriceListRule with id "does-not-exist" not found'
)
})
})
describe("create", () => {
it("should create a priceListRule successfully", async () => {
const [created] = await service.create([
{
price_list_id: "price-list-2",
rule_type_id: "rule-type-1",
},
])
const [priceListRule] = await service.list(
{
id: [created.id],
},
{
relations: ["price_list", "rule_type"],
select: ["price_list.id", "rule_type.id"],
}
)
expect(priceListRule.price_list.id).toEqual("price-list-2")
expect(priceListRule.rule_type.id).toEqual("rule-type-1")
})
})
})
@@ -1,230 +0,0 @@
import { MikroOrmWrapper } from "../../../utils"
import { PriceListService } from "@services"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { createPriceLists } from "../../../__fixtures__/price-list"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
jest.setTimeout(30000)
describe("PriceList Service", () => {
let service: PriceListService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("priceListService")
testManager = await MikroOrmWrapper.forkManager()
await createPriceLists(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("should return list priceLists", async () => {
const priceListResult = await service.list()
expect(priceListResult).toEqual([
expect.objectContaining({
id: "price-list-1",
}),
expect.objectContaining({
id: "price-list-2",
}),
])
})
it("should list pricelists by id", async () => {
const priceListResult = await service.list({
id: ["price-list-1"],
})
expect(priceListResult).toEqual([
expect.objectContaining({
id: "price-list-1",
}),
])
})
})
describe("listAndCount", () => {
it("should return pricelists and count", async () => {
const [priceListResult, count] = await service.listAndCount()
expect(count).toEqual(2)
expect(priceListResult).toEqual([
expect.objectContaining({
id: "price-list-1",
}),
expect.objectContaining({
id: "price-list-2",
}),
])
})
it("should return pricelists and count when filtered", async () => {
const [priceListResult, count] = await service.listAndCount({
id: ["price-list-1"],
})
expect(count).toEqual(1)
expect(priceListResult).toEqual([
expect.objectContaining({
id: "price-list-1",
}),
])
})
it("should return pricelists and count when using skip and take", async () => {
const [priceListResult, count] = await service.listAndCount(
{},
{ skip: 1, take: 1 }
)
expect(count).toEqual(2)
expect(priceListResult).toEqual([
expect.objectContaining({
id: "price-list-2",
}),
])
})
it("should return requested fields", async () => {
const [priceListResult, count] = await service.listAndCount(
{},
{
take: 1,
select: ["id"],
}
)
const serialized = JSON.parse(JSON.stringify(priceListResult))
expect(count).toEqual(2)
expect(serialized).toEqual([
{
id: "price-list-1",
},
])
})
})
describe("retrieve", () => {
const id = "price-list-1"
it("should return priceList for the given id", async () => {
const priceListResult = await service.retrieve(id)
expect(priceListResult).toEqual(
expect.objectContaining({
id,
})
)
})
it("should throw an error when priceList with id does not exist", async () => {
let error
try {
await service.retrieve("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"PriceList with id: does-not-exist was not found"
)
})
it("should throw an error when a id is not provided", async () => {
let error
try {
await service.retrieve(undefined as unknown as string)
} catch (e) {
error = e
}
expect(error.message).toEqual("priceList - id must be defined")
})
})
describe("delete", () => {
const id = "price-list-1"
it("should delete the pricelists given an id successfully", async () => {
await service.delete([id])
const priceListResult = await service.list({
id: [id],
})
expect(priceListResult).toHaveLength(0)
})
})
describe("update", () => {
const id = "price-list-2"
it("should update the starts_at date of the priceList successfully", async () => {
const updateDate = new Date()
await service.update([
{
id,
starts_at: updateDate,
},
])
const priceList = await service.retrieve(id)
expect(priceList.starts_at).toEqual(updateDate)
})
it("should throw an error when a id does not exist", async () => {
let error
try {
await service.update([
{
id: "does-not-exist",
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
'PriceList with id "does-not-exist" not found'
)
})
})
describe("create", () => {
it("should create a priceList successfully", async () => {
const [created] = await service.create([
{
title: "test",
description: "test",
},
])
const [priceList] = await service.list({
id: [created.id],
})
expect(priceList.title).toEqual("test")
})
})
})
@@ -1,331 +0,0 @@
import { PriceSetMoneyAmount } from "@models"
import { CreatePriceRuleDTO } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { PriceRuleService } from "@services"
import { createMoneyAmounts } from "../../../__fixtures__/money-amount"
import { createPriceRules } from "../../../__fixtures__/price-rule"
import { createPriceSets } from "../../../__fixtures__/price-set"
import { createPriceSetMoneyAmounts } from "../../../__fixtures__/price-set-money-amount"
import { createPriceSetMoneyAmountRules } from "../../../__fixtures__/price-set-money-amount-rules"
import { createRuleTypes } from "../../../__fixtures__/rule-type"
import { MikroOrmWrapper } from "../../../utils"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
jest.setTimeout(30000)
describe("PriceRule Service", () => {
let service: PriceRuleService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
testManager = await MikroOrmWrapper.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("priceRuleService")
await createMoneyAmounts(testManager)
await createPriceSets(testManager)
await createRuleTypes(testManager)
await createPriceSetMoneyAmounts(testManager)
await createPriceSetMoneyAmountRules(testManager)
await createPriceRules(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("should list priceRules", async () => {
const priceRuleResult = await service.list()
const serialized = JSON.parse(JSON.stringify(priceRuleResult))
expect(serialized).toEqual([
expect.objectContaining({
id: "price-rule-1",
}),
expect.objectContaining({
id: "price-rule-2",
}),
])
})
it("should list priceRules by id", async () => {
const priceRuleResult = await service.list({
id: ["price-rule-1"],
})
expect(priceRuleResult).toEqual([
expect.objectContaining({
id: "price-rule-1",
}),
])
})
it("should list priceRules with relations and selects", async () => {
const priceRulesResult = await service.list(
{
id: ["price-rule-1"],
},
{
select: ["id", "price_set.id"],
relations: ["price_set"],
}
)
const serialized = JSON.parse(JSON.stringify(priceRulesResult))
expect(serialized).toEqual([
{
id: "price-rule-1",
price_set: {
id: "price-set-1",
},
},
])
})
describe("listAndCount", () => {
it("should return priceRules and count", async () => {
const [priceRulesResult, count] = await service.listAndCount()
expect(count).toEqual(2)
expect(priceRulesResult).toEqual([
expect.objectContaining({
id: "price-rule-1",
}),
expect.objectContaining({
id: "price-rule-2",
}),
])
})
it("should return priceRules and count when filtered", async () => {
const [priceRulesResult, count] = await service.listAndCount({
id: ["price-rule-1"],
})
expect(count).toEqual(1)
expect(priceRulesResult).toEqual([
expect.objectContaining({
id: "price-rule-1",
}),
])
})
it("should list priceRules with relations and selects", async () => {
const [priceRulesResult, count] = await service.listAndCount(
{
id: ["price-rule-1"],
},
{
select: ["id", "price_set.id"],
relations: ["price_set"],
}
)
const serialized = JSON.parse(JSON.stringify(priceRulesResult))
expect(count).toEqual(1)
expect(serialized).toEqual([
{
id: "price-rule-1",
price_set: {
id: "price-set-1",
},
},
])
})
it("should return priceRules and count when using skip and take", async () => {
const [priceRulesResult, count] = await service.listAndCount(
{},
{ skip: 1, take: 1 }
)
expect(count).toEqual(2)
expect(priceRulesResult).toEqual([
expect.objectContaining({
id: "price-rule-2",
}),
])
})
it("should return requested fields", async () => {
const [priceRulesResult, count] = await service.listAndCount(
{},
{
take: 1,
select: ["id"],
}
)
const serialized = JSON.parse(JSON.stringify(priceRulesResult))
expect(count).toEqual(2)
expect(serialized).toEqual([
{
id: "price-rule-1",
},
])
})
})
describe("retrieve", () => {
const id = "price-rule-1"
it("should return priceRule for the given id", async () => {
const priceRule = await service.retrieve(id)
expect(priceRule).toEqual(
expect.objectContaining({
id,
})
)
})
it("should throw an error when priceRule with id does not exist", async () => {
let error
try {
await service.retrieve("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"PriceRule with id: does-not-exist was not found"
)
})
it("should throw an error when a id is not provided", async () => {
let error
try {
await service.retrieve(undefined as unknown as string)
} catch (e) {
error = e
}
expect(error.message).toEqual("priceRule - id must be defined")
})
it("should return priceRule based on config select param", async () => {
const priceRule = await service.retrieve(id, {
select: ["id"],
})
const serialized = JSON.parse(JSON.stringify(priceRule))
expect(serialized).toEqual({
id,
})
})
})
describe("delete", () => {
const id = "price-set-1"
it("should delete the priceRules given an id successfully", async () => {
await service.delete([id])
const priceRules = await service.list({
id: [id],
})
expect(priceRules).toHaveLength(0)
})
})
describe("update", () => {
const id = "price-set-1"
it("should throw an error when a id does not exist", async () => {
let error
try {
await service.update([
{
id: "does-not-exist",
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
'PriceRule with id "does-not-exist" not found'
)
})
})
describe("create", () => {
it("should throw an error when a id does not exist", async () => {
let error
try {
await service.update([
{
random: "does-not-exist",
} as any,
])
} catch (e) {
error = e
}
expect(error.message).toEqual('PriceRule with id "" not found')
})
it("should create a priceRule successfully", async () => {
const [ma] = await createMoneyAmounts(testManager, [
{
amount: 100,
currency_code: "EUR",
},
])
const psma: PriceSetMoneyAmount = testManager.create(
PriceSetMoneyAmount,
{
price_set: "price-set-1",
money_amount: ma.id,
title: "test",
}
)
await testManager.persist(psma).flush()
await service.create([
{
id: "price-rule-new",
price_set_id: "price-set-1",
rule_type_id: "rule-type-1",
value: "region_1",
price_list_id: "test",
price_set_money_amount_id: psma.id,
} as unknown as CreatePriceRuleDTO,
])
const [pricerule] = await service.list({
id: ["price-rule-new"],
})
expect(pricerule).toEqual(
expect.objectContaining({
id: "price-rule-new",
} as unknown as CreatePriceRuleDTO)
)
})
})
})
})
@@ -1,289 +0,0 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { PriceSetMoneyAmountRulesService } from "@services"
import { seedPriceData } from "../../../__fixtures__/seed-price-data"
import { MikroOrmWrapper } from "../../../utils"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
jest.setTimeout(30000)
describe("PriceSetMoneyAmountRules Service", () => {
let service: PriceSetMoneyAmountRulesService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("priceSetMoneyAmountRulesService")
testManager = await MikroOrmWrapper.forkManager()
await seedPriceData(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("should list psmar records", async () => {
const priceSetMoneyAmountRulesResult = await service.list()
expect(priceSetMoneyAmountRulesResult).toEqual([
expect.objectContaining({
id: "psmar-1",
}),
expect.objectContaining({
id: "psmar-2",
}),
expect.objectContaining({
id: "psmar-3",
}),
])
})
it("should list psmar record by id", async () => {
const priceSetMoneyAmountRulesResult = await service.list({
id: ["psmar-1"],
})
expect(priceSetMoneyAmountRulesResult).toEqual([
expect.objectContaining({
id: "psmar-1",
}),
])
})
})
describe("listAndCount", () => {
it("should return psmar records and count", async () => {
const [priceSetMoneyAmountRulesResult, count] =
await service.listAndCount()
expect(count).toEqual(3)
expect(priceSetMoneyAmountRulesResult).toEqual([
expect.objectContaining({
id: "psmar-1",
}),
expect.objectContaining({
id: "psmar-2",
}),
expect.objectContaining({
id: "psmar-3",
}),
])
})
it("should return psmar records and count when filtered", async () => {
const [priceSetMoneyAmountRulesResult, count] =
await service.listAndCount({
id: ["psmar-1"],
})
expect(count).toEqual(1)
expect(priceSetMoneyAmountRulesResult).toEqual([
expect.objectContaining({
id: "psmar-1",
}),
])
})
it("should return psmar and count when using skip and take", async () => {
const [priceSetMoneyAmountRulesResult, count] =
await service.listAndCount({}, { skip: 1, take: 1 })
expect(count).toEqual(3)
expect(priceSetMoneyAmountRulesResult).toEqual([
expect.objectContaining({
id: "psmar-2",
}),
])
})
it("should return requested fields", async () => {
const [priceSetMoneyAmountRulesResult, count] =
await service.listAndCount(
{},
{
take: 1,
select: ["value"],
}
)
const serialized = JSON.parse(
JSON.stringify(priceSetMoneyAmountRulesResult)
)
expect(count).toEqual(3)
expect(serialized).toEqual([
{
id: "psmar-1",
value: "EUR",
},
])
})
})
describe("retrieve", () => {
it("should return priceSetMoneyAmountRules for the given id", async () => {
const priceSetMoneyAmountRules = await service.retrieve("psmar-1")
expect(priceSetMoneyAmountRules).toEqual(
expect.objectContaining({
id: "psmar-1",
})
)
})
it("should throw an error when priceSetMoneyAmountRules with id does not exist", async () => {
let error
try {
await service.retrieve("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"PriceSetMoneyAmountRules with id: does-not-exist was not found"
)
})
it("should throw an error when an id is not provided", async () => {
let error
try {
await service.retrieve(undefined as unknown as string)
} catch (e) {
error = e
}
expect(error.message).toEqual(
"priceSetMoneyAmountRules - id must be defined"
)
})
it("should return priceSetMoneyAmountRules based on config select param", async () => {
const priceSetMoneyAmountRulesResult = await service.retrieve("psmar-1", {
select: ["value"],
})
const serialized = JSON.parse(
JSON.stringify(priceSetMoneyAmountRulesResult)
)
expect(serialized).toEqual({
value: "EUR",
id: "psmar-1",
})
})
})
describe("delete", () => {
const id = "psmar-1"
it("should delete the priceSetMoneyAmountRules given an id successfully", async () => {
await service.delete([id])
const priceSetMoneyAmountRules = await service.list({
id: [id],
})
expect(priceSetMoneyAmountRules).toHaveLength(0)
})
})
describe("update", () => {
const id = "psmar-1"
it("should update the value of the priceSetMoneyAmountRules successfully", async () => {
await service.update([
{
id,
value: "New value",
price_set_money_amount: "price-set-money-amount-CAD",
rule_type: "rule-type-2",
},
])
const psmar = await service.retrieve(id, {
relations: ["price_set_money_amount", "rule_type"],
})
expect(psmar).toEqual(
expect.objectContaining({
id,
value: "New value",
price_set_money_amount: expect.objectContaining({
id: "price-set-money-amount-CAD",
}),
rule_type: expect.objectContaining({
id: "rule-type-2",
}),
})
)
})
it("should throw an error when a id does not exist", async () => {
let error
try {
await service.update([
{
id: "does-not-exist",
value: "random value",
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
'PriceSetMoneyAmountRules with id "does-not-exist" not found'
)
})
})
describe("create", () => {
it("should create a priceSetMoneyAmountRules successfully", async () => {
const created = await service.create([
{
price_set_money_amount: "price-set-money-amount-EUR",
rule_type: "rule-type-2",
value: "New priceSetMoneyAmountRule",
},
])
const [priceSetMoneyAmountRules] = await service.list(
{
id: [created[0]?.id],
},
{
relations: ["price_set_money_amount", "rule_type"],
}
)
expect(priceSetMoneyAmountRules).toEqual(
expect.objectContaining({
id: created[0]?.id,
value: "New priceSetMoneyAmountRule",
price_set_money_amount: expect.objectContaining({
id: "price-set-money-amount-EUR",
}),
rule_type: expect.objectContaining({
id: "rule-type-2",
}),
})
)
})
})
})
@@ -1,392 +0,0 @@
import { CreatePriceSetDTO } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { MoneyAmount, PriceSet } from "@models"
import { PriceSetService } from "@services"
import { createMoneyAmounts } from "../../../__fixtures__/money-amount"
import { createPriceSets } from "../../../__fixtures__/price-set"
import { MikroOrmWrapper } from "../../../utils"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
jest.setTimeout(30000)
describe("PriceSet Service", () => {
let service: PriceSetService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let data!: PriceSet[]
let moneyAmountsData!: MoneyAmount[]
const moneyAmountsInputData = [
{
id: "money-amount-USD",
currency_code: "USD",
amount: 500,
min_quantity: 1,
max_quantity: 10,
},
]
const priceSetInputData = [
{
id: "price-set-1",
prices: [
{
id: "money-amount-USD",
currency_code: "EUR",
amount: 100,
},
],
},
{
id: "price-set-2",
prices: [],
},
{
id: "price-set-3",
prices: [],
},
]
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
testManager = await MikroOrmWrapper.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("priceSetService")
moneyAmountsData = await createMoneyAmounts(
testManager,
moneyAmountsInputData
)
data = await createPriceSets(testManager, priceSetInputData)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("should list priceSets", async () => {
const priceSetsResult = await service.list()
const serialized = JSON.parse(JSON.stringify(priceSetsResult))
expect(serialized).toEqual([
expect.objectContaining({
id: "price-set-1",
}),
expect.objectContaining({
id: "price-set-2",
}),
expect.objectContaining({
id: "price-set-3",
}),
])
})
it("should list priceSets by id", async () => {
const priceSetsResult = await service.list({
id: ["price-set-1"],
})
expect(priceSetsResult).toEqual([
expect.objectContaining({
id: "price-set-1",
}),
])
})
it("should list priceSets with relations and selects", async () => {
const priceSetsResult = await service.list(
{
id: ["price-set-1"],
},
{
select: ["id", "money_amounts.id"],
relations: ["money_amounts"],
}
)
const serialized = JSON.parse(JSON.stringify(priceSetsResult))
expect(serialized).toEqual([
{
id: "price-set-1",
money_amounts: [
expect.objectContaining({
id: "money-amount-USD",
}),
],
},
])
})
it("should scope priceSets with currency_code of money amounts", async () => {
const priceSetsResult = await service.list(
{
money_amounts: {
currency_code: ["USD"],
},
},
{
select: ["id", "money_amounts.id"],
relations: ["money_amounts"],
}
)
const serialized = JSON.parse(JSON.stringify(priceSetsResult))
expect(serialized).toEqual([
{
id: "price-set-1",
money_amounts: [
expect.objectContaining({
id: "money-amount-USD",
}),
],
},
])
})
})
it("should not return price sets if money amounts with a currency code dont exist", async () => {
const priceSetsResult = await service.list(
{
money_amounts: {
currency_code: ["DOESNOTEXIST"],
},
},
{
select: ["id", "money_amounts.id"],
relations: ["money_amounts"],
}
)
const serialized = JSON.parse(JSON.stringify(priceSetsResult))
expect(serialized).toEqual([])
})
describe("listAndCount", () => {
it("should return priceSets and count", async () => {
const [priceSetsResult, count] = await service.listAndCount()
expect(count).toEqual(3)
expect(priceSetsResult).toEqual([
expect.objectContaining({
id: "price-set-1",
}),
expect.objectContaining({
id: "price-set-2",
}),
expect.objectContaining({
id: "price-set-3",
}),
])
})
it("should return priceSets and count when filtered", async () => {
const [priceSetsResult, count] = await service.listAndCount({
id: ["price-set-1"],
})
expect(count).toEqual(1)
expect(priceSetsResult).toEqual([
expect.objectContaining({
id: "price-set-1",
}),
])
})
it("should list priceSets with relations and selects", async () => {
const [priceSetsResult, count] = await service.listAndCount(
{
id: ["price-set-1"],
},
{
select: ["id", "min_quantity", "money_amounts.id"],
relations: ["money_amounts"],
}
)
const serialized = JSON.parse(JSON.stringify(priceSetsResult))
expect(count).toEqual(1)
expect(serialized).toEqual([
{
id: "price-set-1",
money_amounts: [
expect.objectContaining({
id: "money-amount-USD",
}),
],
},
])
})
it("should return priceSets and count when using skip and take", async () => {
const [priceSetsResult, count] = await service.listAndCount(
{},
{ skip: 1, take: 1 }
)
expect(count).toEqual(3)
expect(priceSetsResult).toEqual([
expect.objectContaining({
id: "price-set-2",
}),
])
})
it("should return requested fields", async () => {
const [priceSetsResult, count] = await service.listAndCount(
{},
{
take: 1,
select: ["id"],
}
)
const serialized = JSON.parse(JSON.stringify(priceSetsResult))
expect(count).toEqual(3)
expect(serialized).toEqual([
{
id: "price-set-1",
},
])
})
})
describe("retrieve", () => {
const id = "price-set-1"
it("should return priceSet for the given id", async () => {
const priceSet = await service.retrieve(id)
expect(priceSet).toEqual(
expect.objectContaining({
id,
})
)
})
it("should throw an error when priceSet with id does not exist", async () => {
let error
try {
await service.retrieve("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"PriceSet with id: does-not-exist was not found"
)
})
it("should throw an error when a id is not provided", async () => {
let error
try {
await service.retrieve(undefined as unknown as string)
} catch (e) {
error = e
}
expect(error.message).toEqual("priceSet - id must be defined")
})
it("should return priceSet based on config select param", async () => {
const priceSet = await service.retrieve(id, {
select: ["id"],
})
const serialized = JSON.parse(JSON.stringify(priceSet))
expect(serialized).toEqual({
id,
})
})
})
describe("delete", () => {
const id = "price-set-1"
it("should delete the priceSets given an id successfully", async () => {
await service.delete([id])
const priceSets = await service.list({
id: [id],
})
expect(priceSets).toHaveLength(0)
})
})
describe("update", () => {
const id = "price-set-1"
it("should throw an error when a id does not exist", async () => {
let error
try {
await service.update([
{
id: "does-not-exist",
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
'PriceSet with id "does-not-exist" not found'
)
})
})
describe("create", () => {
it("should throw an error when a id does not exist", async () => {
let error
try {
await service.update([
{
random: "does-not-exist",
} as any,
])
} catch (e) {
error = e
}
expect(error.message).toEqual('PriceSet with id "" not found')
})
it("should create a priceSet successfully", async () => {
await service.create([
{
id: "price-set-new",
} as unknown as CreatePriceSetDTO,
])
const [priceSet] = await service.list({
id: ["price-set-new"],
})
expect(priceSet).toEqual(
expect.objectContaining({
id: "price-set-new",
} as unknown as CreatePriceSetDTO)
)
})
})
})
@@ -5,13 +5,9 @@ import {
PricingTypes,
} from "@medusajs/types"
import { PriceListType } from "@medusajs/utils"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { PriceSet } from "@models"
import { seedPriceData } from "../../../__fixtures__/seed-price-data"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { initModules } from "medusa-test-utils"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
@@ -52,37 +48,13 @@ const createPriceLists = async (
])
}
describe("PricingModule Service - Calculate Price", () => {
let service: IPricingModuleService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let data!: PriceSet[]
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRICING]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = MikroOrmWrapper.forkManager()
testManager = MikroOrmWrapper.forkManager()
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
moduleIntegrationTestRunner({
moduleName: Modules.PRICING,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPricingModuleService>) => {
describe("PricingModule Service - Calculate Price", () => {
describe("calculatePrices", () => {
beforeEach(async () => {
const moneyAmountsData = [
@@ -219,7 +191,8 @@ describe("PricingModule Service - Calculate Price", () => {
},
{
id: "psma-region_id_company_id-PL-EUR-customer-group",
title: "psma PLN - region_id PL with EUR currency for customer group",
title:
"psma PLN - region_id PL with EUR currency for customer group",
price_set: "price-set-PLN",
money_amount: "money-amount-region_id-PL-EUR-customer-group",
rules_count: 3,
@@ -318,7 +291,8 @@ describe("PricingModule Service - Calculate Price", () => {
rule_type_id: "rule-type-region_id",
value: "PL",
price_list_id: "test",
price_set_money_amount_id: "psma-region_id_company_id-PL-EUR-4-qty",
price_set_money_amount_id:
"psma-region_id_company_id-PL-EUR-4-qty",
},
{
id: "price-rule-region_id-company_id-PLN-4-qty",
@@ -326,7 +300,8 @@ describe("PricingModule Service - Calculate Price", () => {
rule_type_id: "rule-type-company_id",
value: "medusa-company-id",
price_list_id: "test",
price_set_money_amount_id: "psma-region_id_company_id-PL-EUR-4-qty",
price_set_money_amount_id:
"psma-region_id_company_id-PL-EUR-4-qty",
},
{
id: "price-rule-region_id-currency_customer_group_code-PL",
@@ -1064,7 +1039,11 @@ describe("PricingModule Service - Calculate Price", () => {
const priceSetsResult = await service.calculatePrices(
{ id: ["price-set-EUR", "price-set-PLN"] },
{
context: { currency_code: "PLN", region_id: "PL", city: "Berlin" },
context: {
currency_code: "PLN",
region_id: "PL",
city: "Berlin",
},
}
)
@@ -1989,4 +1968,6 @@ describe("PricingModule Service - Calculate Price", () => {
})
})
})
})
},
})
@@ -1,50 +1,27 @@
import { Modules } from "@medusajs/modules-sdk"
import { IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { MoneyAmount } from "@models"
import { initModules } from "medusa-test-utils"
import { createMoneyAmounts } from "../../../__fixtures__/money-amount"
import { createPriceRules } from "../../../__fixtures__/price-rule"
import { createPriceSets } from "../../../__fixtures__/price-set"
import { createPriceSetMoneyAmounts } from "../../../__fixtures__/price-set-money-amount"
import { createPriceSetMoneyAmountRules } from "../../../__fixtures__/price-set-money-amount-rules"
import { createRuleTypes } from "../../../__fixtures__/rule-type"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
describe("PricingModule Service - MoneyAmount", () => {
let service: IPricingModuleService
moduleIntegrationTestRunner({
moduleName: Modules.PRICING,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPricingModuleService>) => {
describe("PricingModule Service - MoneyAmount", () => {
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let data!: MoneyAmount[]
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRICING]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = MikroOrmWrapper.forkManager()
testManager = MikroOrmWrapper.forkManager()
data = await createMoneyAmounts(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
testManager = await MikroOrmWrapper.forkManager()
await createMoneyAmounts(testManager)
})
describe("listMoneyAmounts", () => {
@@ -433,4 +410,6 @@ describe("PricingModule Service - MoneyAmount", () => {
)
})
})
})
},
})
@@ -1,50 +1,28 @@
import { MikroOrmWrapper } from "../../../utils"
import { IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { createPriceLists } from "../../../__fixtures__/price-list"
import { createPriceListRules } from "../../../__fixtures__/price-list-rules"
import { createRuleTypes } from "../../../__fixtures__/rule-type"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { Modules } from "@medusajs/modules-sdk"
import { initModules } from "medusa-test-utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
describe("PriceListRule Service", () => {
let service: IPricingModuleService
moduleIntegrationTestRunner({
moduleName: Modules.PRICING,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPricingModuleService>) => {
describe("PriceListRule Service", () => {
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRICING]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
testManager = await MikroOrmWrapper.forkManager()
await createRuleTypes(testManager)
await createPriceLists(testManager)
await createPriceListRules(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("should list priceListRules", async () => {
const priceListRuleResult = await service.listPriceListRules()
@@ -355,4 +333,6 @@ describe("PriceListRule Service", () => {
])
})
})
})
},
})
@@ -1,39 +1,20 @@
import { MikroOrmWrapper } from "../../../utils"
import { Modules } from "@medusajs/modules-sdk"
import { IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { initModules } from "medusa-test-utils"
import { createPriceLists } from "../../../__fixtures__/price-list"
import { createPriceSets } from "../../../__fixtures__/price-set"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
describe("PriceList Service", () => {
let service: IPricingModuleService
let testManager: SqlEntityManager
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRICING]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
moduleIntegrationTestRunner({
moduleName: Modules.PRICING,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPricingModuleService>) => {
describe("PriceList Service", () => {
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
await MikroOrmWrapper.forkManager()
testManager = await MikroOrmWrapper.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
await createPriceSets(testManager)
await createPriceLists(testManager)
await service.createRuleTypes([
@@ -48,10 +29,6 @@ describe("PriceList Service", () => {
])
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("should list priceLists", async () => {
const priceListResult = await service.listPriceLists()
@@ -81,7 +58,8 @@ describe("PriceList Service", () => {
describe("listAndCount", () => {
it("should return pricelists and count", async () => {
const [priceListResult, count] = await service.listAndCountPriceLists()
const [priceListResult, count] =
await service.listAndCountPriceLists()
expect(count).toEqual(2)
expect(priceListResult).toEqual([
@@ -95,9 +73,11 @@ describe("PriceList Service", () => {
})
it("should return pricelists and count when filtered", async () => {
const [priceListResult, count] = await service.listAndCountPriceLists({
const [priceListResult, count] = await service.listAndCountPriceLists(
{
id: ["price-list-1"],
})
}
)
expect(count).toEqual(1)
expect(priceListResult).toEqual([
@@ -863,4 +843,6 @@ describe("PriceList Service", () => {
)
})
})
})
},
})
@@ -8,35 +8,21 @@ import { createPriceSets } from "../../../__fixtures__/price-set"
import { createPriceSetMoneyAmounts } from "../../../__fixtures__/price-set-money-amount"
import { createPriceSetMoneyAmountRules } from "../../../__fixtures__/price-set-money-amount-rules"
import { createRuleTypes } from "../../../__fixtures__/rule-type"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { initModules } from "medusa-test-utils"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
describe("PricingModule Service - PriceRule", () => {
let service: IPricingModuleService
moduleIntegrationTestRunner({
moduleName: Modules.PRICING,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPricingModuleService>) => {
describe("PricingModule Service - PriceRule", () => {
let testManager: SqlEntityManager
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRICING]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
testManager = MikroOrmWrapper.forkManager()
testManager = await MikroOrmWrapper.forkManager()
await createMoneyAmounts(testManager)
await createPriceSets(testManager)
@@ -46,10 +32,6 @@ describe("PricingModule Service - PriceRule", () => {
await createPriceRules(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("should list priceRules", async () => {
const PriceRulesResult = await service.listPriceRules()
@@ -102,7 +84,8 @@ describe("PricingModule Service - PriceRule", () => {
describe("listAndCount", () => {
it("should return priceRules and count", async () => {
const [priceRulesResult, count] = await service.listAndCountPriceRules()
const [priceRulesResult, count] =
await service.listAndCountPriceRules()
expect(count).toEqual(2)
expect(priceRulesResult).toEqual([
@@ -116,7 +99,8 @@ describe("PricingModule Service - PriceRule", () => {
})
it("should return priceRules and count when filtered", async () => {
const [priceRulesResult, count] = await service.listAndCountPriceRules({
const [priceRulesResult, count] =
await service.listAndCountPriceRules({
id: ["price-rule-1"],
})
@@ -129,7 +113,8 @@ describe("PricingModule Service - PriceRule", () => {
})
it("should list PriceRules with relations and selects", async () => {
const [PriceRulesResult, count] = await service.listAndCountPriceRules(
const [PriceRulesResult, count] =
await service.listAndCountPriceRules(
{
id: ["price-rule-1"],
},
@@ -153,10 +138,8 @@ describe("PricingModule Service - PriceRule", () => {
})
it("should return PriceRules and count when using skip and take", async () => {
const [PriceRulesResult, count] = await service.listAndCountPriceRules(
{},
{ skip: 1, take: 1 }
)
const [PriceRulesResult, count] =
await service.listAndCountPriceRules({}, { skip: 1, take: 1 })
expect(count).toEqual(2)
expect(PriceRulesResult).toEqual([
@@ -167,7 +150,8 @@ describe("PricingModule Service - PriceRule", () => {
})
it("should return requested fields", async () => {
const [PriceRulesResult, count] = await service.listAndCountPriceRules(
const [PriceRulesResult, count] =
await service.listAndCountPriceRules(
{},
{
take: 1,
@@ -334,4 +318,6 @@ describe("PricingModule Service - PriceRule", () => {
})
})
})
})
},
})
@@ -5,37 +5,20 @@ import { createPriceSets } from "../../../__fixtures__/price-set"
import { createPriceSetMoneyAmounts } from "../../../__fixtures__/price-set-money-amount"
import { createPriceSetMoneyAmountRules } from "../../../__fixtures__/price-set-money-amount-rules"
import { createRuleTypes } from "../../../__fixtures__/rule-type"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { initModules } from "medusa-test-utils"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
describe("PricingModule Service - PriceSetMoneyAmountRules", () => {
let service: IPricingModuleService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRICING]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
moduleIntegrationTestRunner({
moduleName: Modules.PRICING,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPricingModuleService>) => {
describe("PricingModule Service - PriceSetMoneyAmountRules", () => {
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
testManager = await MikroOrmWrapper.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
await createMoneyAmounts(testManager)
await createPriceSets(testManager)
@@ -44,10 +27,6 @@ describe("PricingModule Service - PriceSetMoneyAmountRules", () => {
await createPriceSetMoneyAmountRules(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("listPriceSetMoneyAmountRules", () => {
it("should list psmar records", async () => {
const priceSetMoneyAmountRulesResult =
@@ -294,4 +273,6 @@ describe("PricingModule Service - PriceSetMoneyAmountRules", () => {
)
})
})
})
},
})
@@ -4,14 +4,11 @@ import {
IPricingModuleService,
} from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { PriceSet } from "@models"
import { PriceSetRuleType } from "../../../../src"
import { seedPriceData } from "../../../__fixtures__/seed-price-data"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { initModules } from "medusa-test-utils"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
@@ -22,7 +19,7 @@ async function createPriceSetPriceRules(
const priceSetRules: PriceSetRuleType[] = []
for (let priceSetRuleData of priceSetRulesData) {
const priceRule = manager.create(PriceSetRuleType, priceSetRuleData)
const priceRule = manager.create(PriceSetRuleType, priceSetRuleData as any)
priceSetRules.push(priceRule)
}
@@ -30,31 +27,15 @@ async function createPriceSetPriceRules(
await manager.persistAndFlush(priceSetRules)
}
describe("PricingModule Service - PriceSet", () => {
let service: IPricingModuleService
let repositoryManager: SqlEntityManager
let data!: PriceSet[]
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRICING]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
moduleIntegrationTestRunner({
moduleName: Modules.PRICING,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPricingModuleService>) => {
describe("PricingModule Service - PriceSet", () => {
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = MikroOrmWrapper.forkManager()
const testManager = MikroOrmWrapper.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
await seedPriceData(testManager)
await createPriceSetPriceRules(testManager, [
{
@@ -68,10 +49,6 @@ describe("PricingModule Service - PriceSet", () => {
] as unknown as CreatePriceSetRuleTypeDTO[])
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("list priceSets", async () => {
const priceSetsResult = await service.list()
@@ -118,7 +95,10 @@ describe("PricingModule Service - PriceSet", () => {
{
id: "price-set-1",
money_amounts: [
expect.objectContaining({ id: "money-amount-USD", amount: 500 }),
expect.objectContaining({
id: "money-amount-USD",
amount: 500,
}),
],
},
])
@@ -173,7 +153,9 @@ describe("PricingModule Service - PriceSet", () => {
expect(serialized).toEqual([
{
id: "price-set-1",
money_amounts: [expect.objectContaining({ id: "money-amount-USD" })],
money_amounts: [
expect.objectContaining({ id: "money-amount-USD" }),
],
},
])
})
@@ -779,4 +761,6 @@ describe("PricingModule Service - PriceSet", () => {
)
})
})
})
},
})
@@ -1,43 +1,21 @@
import { IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { createRuleTypes } from "../../../__fixtures__/rule-type"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { initModules } from "medusa-test-utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { Modules } from "@medusajs/modules-sdk"
import { IPricingModuleService } from "@medusajs/types"
describe("PricingModuleService ruleType", () => {
let service: IPricingModuleService
let testManager: SqlEntityManager
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRICING]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
moduleIntegrationTestRunner({
moduleName: Modules.PRICING,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPricingModuleService>) => {
describe("PricingModuleService ruleType", () => {
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
MikroOrmWrapper.forkManager()
testManager = MikroOrmWrapper.forkManager()
const testManager = MikroOrmWrapper.forkManager()
await createRuleTypes(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("listRuleTypes", () => {
it("should list rule types", async () => {
const ruleTypeResult = await service.listRuleTypes()
@@ -258,4 +236,6 @@ describe("PricingModuleService ruleType", () => {
)
})
})
})
},
})
@@ -1,274 +0,0 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { RuleTypeService } from "@services"
import { createRuleTypes } from "../../../__fixtures__/rule-type"
import { MikroOrmWrapper } from "../../../utils"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
jest.setTimeout(30000)
describe("RuleType Service", () => {
let service: RuleTypeService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("ruleTypeService")
testManager = await MikroOrmWrapper.forkManager()
await createRuleTypes(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("list rule types", async () => {
const ruleTypeResult = await service.list()
expect(ruleTypeResult).toEqual([
expect.objectContaining({
id: "rule-type-1",
name: "rule 1",
}),
expect.objectContaining({
id: "rule-type-2",
name: "rule 2",
}),
])
})
it("list rule types by id", async () => {
const ruleTypeResult = await service.list({ id: ["rule-type-1"] })
expect(ruleTypeResult).toEqual([
expect.objectContaining({
id: "rule-type-1",
name: "rule 1",
}),
])
})
})
describe("listAndCount", () => {
it("should return rule types and count", async () => {
const [ruleTypeResult, count] = await service.listAndCount()
expect(count).toEqual(2)
expect(ruleTypeResult).toEqual([
expect.objectContaining({
id: "rule-type-1",
name: "rule 1",
}),
expect.objectContaining({
id: "rule-type-2",
name: "rule 2",
}),
])
})
it("should return rule types and count when filtered", async () => {
const [ruleTypeResult, count] = await service.listAndCount({
id: ["rule-type-1"],
})
expect(count).toEqual(1)
expect(ruleTypeResult).toEqual([
expect.objectContaining({
id: "rule-type-1",
name: "rule 1",
}),
])
})
it("should return rule types and count when using skip and take", async () => {
const [ruleTypeResult, count] = await service.listAndCount(
{},
{ skip: 1, take: 1 }
)
expect(count).toEqual(2)
expect(ruleTypeResult).toEqual([
expect.objectContaining({
id: "rule-type-2",
name: "rule 2",
}),
])
})
it("should return requested fields", async () => {
const [ruleTypeResult, count] = await service.listAndCount(
{},
{
take: 1,
select: ["name"],
}
)
const serialized = JSON.parse(JSON.stringify(ruleTypeResult))
expect(count).toEqual(2)
expect(serialized).toEqual([
{
id: "rule-type-1",
name: "rule 1",
},
])
})
})
describe("retrieve", () => {
it("should return ruleType for the given id", async () => {
const ruleType = await service.retrieve("rule-type-1")
expect(ruleType).toEqual(
expect.objectContaining({
id: "rule-type-1",
name: "rule 1",
})
)
})
it("should throw an error when ruleType with id does not exist", async () => {
let error
try {
await service.retrieve("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"RuleType with id: does-not-exist was not found"
)
})
it("should throw an error when an id is not provided", async () => {
let error
try {
await service.retrieve(undefined as unknown as string)
} catch (e) {
error = e
}
expect(error.message).toEqual("ruleType - id must be defined")
})
it("should return ruleType based on config select param", async () => {
const ruleTypeResult = await service.retrieve("rule-type-1", {
select: ["name"],
})
const serialized = JSON.parse(JSON.stringify(ruleTypeResult))
expect(serialized).toEqual({
name: "rule 1",
id: "rule-type-1",
})
})
})
describe("delete", () => {
const id = "rule-type-1"
it("should delete the ruleTypes given an id successfully", async () => {
await service.delete([id])
const ruleTypes = await service.list({
id: [id],
})
expect(ruleTypes).toHaveLength(0)
})
})
describe("update", () => {
const id = "rule-type-1"
it("should update the name of the ruleType successfully", async () => {
await service.update([
{
id,
name: "rule 3",
},
])
const ruletype = await service.retrieve(id)
expect(ruletype.name).toEqual("rule 3")
})
it("should throw an error when a id does not exist", async () => {
let error
try {
await service.update([
{
id: "does-not-exist",
name: "rule 3",
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
'RuleType with id "does-not-exist" not found'
)
})
})
describe("create", () => {
it("should create a ruleType successfully", async () => {
await service.create([
{
name: "Test Rule",
rule_attribute: "region_id",
},
])
const [ruleType] = await service.list({
name: ["Test Rule"],
})
expect(ruleType).toEqual(
expect.objectContaining({
name: "Test Rule",
rule_attribute: "region_id",
})
)
})
it("should throw an error when using one of the reserved keywords", async () => {
let error
try {
await service.create([
{
name: "Test Rule",
rule_attribute: "currency_code",
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
"Can't create rule_attribute with reserved keywords [quantity, currency_code, price_list_id] - currency_code"
)
})
})
})
@@ -1,6 +0,0 @@
if (typeof process.env.DB_TEMP_NAME === "undefined") {
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
process.env.DB_TEMP_NAME = `medusa-pricing-integration-${tempName}`
}
process.env.MEDUSA_PRICING_DB_SCHEMA = "public"
@@ -1,3 +0,0 @@
import { JestUtils } from "medusa-test-utils"
JestUtils.afterAllHookDropDatabase()
@@ -1,6 +0,0 @@
import { ModuleServiceInitializeOptions } from "@medusajs/types"
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
schema: "public",
clientUrl: "medusa-pricing-test",
}
@@ -1,18 +0,0 @@
import { TestDatabaseUtils } from "medusa-test-utils"
import * as PricingModels from "@models"
const pathToMigrations = "../../src/migrations"
const mikroOrmEntities = PricingModels as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper({
mikroOrmEntities,
pathToMigrations,
})
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig({
mikroOrmEntities,
pathToMigrations,
})
export const DB_URL = TestDatabaseUtils.getDatabaseURL()
@@ -1,31 +0,0 @@
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
import { DB_URL } from "./database"
export function getInitModuleConfig() {
const moduleOptions = {
defaultAdapterOptions: {
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_PRICING_DB_SCHEMA,
},
},
}
const modulesConfig_ = {
[Modules.PRODUCT]: true,
[Modules.PRICING]: {
definition: ModulesDefinition[Modules.PRICING],
options: moduleOptions,
},
}
return {
modulesConfig: modulesConfig_,
databaseConfig: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_PRICING_DB_SCHEMA,
},
joinerConfig: [],
}
}
@@ -1 +0,0 @@
export * from "./database"
-2
View File
@@ -18,6 +18,4 @@ module.exports = {
testEnvironment: `node`,
moduleFileExtensions: [`js`, `ts`],
modulePathIgnorePatterns: ["dist/"],
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
}
@@ -1,43 +0,0 @@
import {
EmitData,
EventBusTypes,
IEventBusModuleService,
Message,
Subscriber,
} from "@medusajs/types"
export class EventBusService implements IEventBusModuleService {
emit<T>(
eventName: string,
data: T,
options?: Record<string, unknown>
): Promise<void>
emit<T>(data: EmitData<T>[]): Promise<void>
emit<T>(data: Message<T>[]): Promise<void>
async emit<
T,
TInput extends
| string
| EventBusTypes.EmitData<T>[]
| EventBusTypes.Message<T>[] = string
>(
eventOrData: TInput,
data?: T,
options: Record<string, unknown> = {}
): Promise<void> {}
subscribe(event: string | symbol, subscriber: Subscriber): this {
return this
}
unsubscribe(
event: string | symbol,
subscriber: Subscriber,
context?: EventBusTypes.SubscriberContext
): this {
return this
}
withTransaction() {}
}
@@ -1,482 +0,0 @@
import { MedusaModule, Modules } from "@medusajs/modules-sdk"
import { IProductModuleService } from "@medusajs/types"
import { kebabCase } from "@medusajs/utils"
import { knex } from "@mikro-orm/knex"
import { initModules } from "medusa-test-utils"
import * as CustomRepositories from "../__fixtures__/module"
import {
buildProductAndRelationsData,
createProductAndTags,
} from "../__fixtures__/product"
import { productsData } from "../__fixtures__/product/data"
import { DB_URL, TestDatabase } from "../utils"
import { getInitModuleConfig } from "../utils/get-init-module-config"
const sharedPgConnection = knex<any, any>({
client: "pg",
searchPath: process.env.MEDUSA_PRODUCT_DB_SCHEMA,
connection: {
connectionString: DB_URL,
},
})
const beforeEach_ = async () => {
await TestDatabase.setupDatabase()
return await TestDatabase.forkManager()
}
const afterEach_ = async () => {
await TestDatabase.clearDatabase()
}
describe("Product module", function () {
describe("Using built-in data access layer", function () {
let module: IProductModuleService
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
module = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
const testManager = await beforeEach_()
await createProductAndTags(testManager, productsData)
})
afterEach(afterEach_)
it("should initialize", async () => {
expect(module).toBeDefined()
})
it("should have a connection that is not the shared connection", async () => {
expect(
(module as any).baseRepository_.manager_.getConnection().client
).not.toEqual(sharedPgConnection)
})
it("should return a list of product", async () => {
const products = await module.list()
expect(products).toHaveLength(3)
})
})
describe("Using custom data access layer", function () {
let module
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig({
repositories: CustomRepositories,
})
const { medusaApp, shutdown } = await initModules(initModulesConfig)
module = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
const testManager = await beforeEach_()
await createProductAndTags(testManager, productsData)
})
afterEach(afterEach_)
it("should initialize", async () => {
expect(module).toBeDefined()
})
it("should have a connection that is not the shared connection", async () => {
expect(
(module as any).baseRepository_.manager_.getConnection().client
).not.toEqual(sharedPgConnection)
})
it("should return a list of product", async () => {
const products = await module.list()
expect(module.productService_.productRepository_.find).toHaveBeenCalled()
expect(products).toHaveLength(0)
})
})
describe("Using custom data access layer and manager", function () {
let module
let shutdownFunc: () => Promise<void>
afterEach(async () => {
await shutdownFunc()
})
beforeEach(async () => {
const testManager = await beforeEach_()
await createProductAndTags(testManager, productsData)
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig({
manager: testManager,
repositories: CustomRepositories,
})
const { medusaApp, shutdown } = await initModules(initModulesConfig)
module = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterEach(afterEach_)
it("should initialize and return a list of product", async () => {
expect(module).toBeDefined()
})
it("should have a connection that is not the shared connection", async () => {
expect(
(module as any).baseRepository_.manager_.getConnection().client
).not.toEqual(sharedPgConnection)
})
it("should return a list of product", async () => {
const products = await module.list()
expect(module.productService_.productRepository_.find).toHaveBeenCalled()
expect(products).toHaveLength(0)
})
})
describe("Using an existing connection", function () {
let module: IProductModuleService
let shutdownFunc: () => Promise<void>
afterEach(async () => {
await shutdownFunc()
})
beforeEach(async () => {
const testManager = await beforeEach_()
await createProductAndTags(testManager, productsData)
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig({
database: {
connection: sharedPgConnection,
},
})
const { medusaApp, shutdown } = await initModules(initModulesConfig)
module = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterEach(afterEach_)
it("should initialize and return a list of product", async () => {
expect(module).toBeDefined()
})
it("should have a connection that is the shared connection", async () => {
expect(
JSON.stringify(
(module as any).baseRepository_.manager_.getConnection().client
)
).toEqual(JSON.stringify(sharedPgConnection))
})
})
describe("create", function () {
let module: IProductModuleService
let images = ["image-1"]
let shutdownFunc: () => Promise<void>
afterEach(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await beforeEach_()
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig({
database: {
connection: sharedPgConnection,
},
})
const { medusaApp, shutdown } = await initModules(initModulesConfig)
module = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterEach(afterEach_)
it("should create a product", async () => {
const data = buildProductAndRelationsData({
images,
thumbnail: images[0],
})
const productsCreated = await module.create([data])
const products = await module.list(
{ id: productsCreated[0].id },
{
relations: [
"images",
"categories",
"variants",
"variants.options",
"options",
"options.values",
"tags",
"type",
],
}
)
expect(products).toHaveLength(1)
expect(products[0].images).toHaveLength(1)
expect(products[0].options).toHaveLength(1)
expect(products[0].tags).toHaveLength(1)
expect(products[0].categories).toHaveLength(0)
expect(products[0].variants).toHaveLength(1)
expect(products[0]).toEqual(
expect.objectContaining({
id: expect.any(String),
title: data.title,
handle: kebabCase(data.title),
description: data.description,
subtitle: data.subtitle,
is_giftcard: data.is_giftcard,
discountable: data.discountable,
thumbnail: images[0],
status: data.status,
images: expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
url: images[0],
}),
]),
options: expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
title: data.options[0].title,
values: expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
value: data.variants[0].options?.[0].value,
}),
]),
}),
]),
tags: expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
value: data.tags[0].value,
}),
]),
type: expect.objectContaining({
id: expect.any(String),
value: data.type.value,
}),
variants: expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
title: data.variants[0].title,
sku: data.variants[0].sku,
allow_backorder: false,
manage_inventory: true,
inventory_quantity: 100,
variant_rank: 0,
options: expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
value: data.variants[0].options?.[0].value,
}),
]),
}),
]),
})
)
})
})
describe("softDelete", function () {
let module: IProductModuleService
let images = ["image-1"]
let shutdownFunc: () => Promise<void>
afterEach(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await beforeEach_()
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
module = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterEach(afterEach_)
it("should soft delete a product and its cascaded relations", async () => {
const data = buildProductAndRelationsData({
images,
thumbnail: images[0],
})
const products = await module.create([data])
await module.softDelete([products[0].id])
const deletedProducts = await module.list(
{ id: products[0].id },
{
relations: [
"variants",
"variants.options",
"options",
"options.values",
],
withDeleted: true,
}
)
expect(deletedProducts).toHaveLength(1)
expect(deletedProducts[0].deleted_at).not.toBeNull()
for (const option of deletedProducts[0].options) {
expect(option.deleted_at).not.toBeNull()
}
const productOptionsValues = deletedProducts[0].options
.map((o) => o.values)
.flat()
for (const optionValue of productOptionsValues) {
expect(optionValue.deleted_at).not.toBeNull()
}
for (const variant of deletedProducts[0].variants) {
expect(variant.deleted_at).not.toBeNull()
}
const variantsOptions = deletedProducts[0].options
.map((o) => o.values)
.flat()
for (const option of variantsOptions) {
expect(option.deleted_at).not.toBeNull()
}
})
})
describe("restore", function () {
let module: IProductModuleService
let images = ["image-1"]
let shutdownFunc: () => Promise<void>
afterEach(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await beforeEach_()
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
module = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterEach(afterEach_)
it("should restore a soft deleted product and its cascaded relations", async () => {
const data = buildProductAndRelationsData({
images,
thumbnail: images[0],
})
const products = await module.create([data])
await module.softDelete([products[0].id])
await module.restore([products[0].id])
const deletedProducts = await module.list(
{ id: products[0].id },
{
relations: [
"variants",
"variants.options",
"variants.options",
"options",
"options.values",
],
withDeleted: true,
}
)
expect(deletedProducts).toHaveLength(1)
expect(deletedProducts[0].deleted_at).toBeNull()
for (const option of deletedProducts[0].options) {
expect(option.deleted_at).toBeNull()
}
const productOptionsValues = deletedProducts[0].options
.map((o) => o.values)
.flat()
for (const optionValue of productOptionsValues) {
expect(optionValue.deleted_at).toBeNull()
}
for (const variant of deletedProducts[0].variants) {
expect(variant.deleted_at).toBeNull()
}
const variantsOptions = deletedProducts[0].options
.map((o) => o.values)
.flat()
for (const option of variantsOptions) {
expect(option.deleted_at).toBeNull()
}
})
})
})
@@ -1,6 +1,3 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { ProductCategory } from "@models"
import { ProductCategoryService } from "@services"
import { createProductCategories } from "../../../__fixtures__/product-category"
@@ -8,41 +5,29 @@ import {
productCategoriesData,
productCategoriesRankData,
} from "../../../__fixtures__/product-category/data"
import { TestDatabase } from "../../../utils"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { IProductModuleService } from "@medusajs/types"
jest.setTimeout(30000)
describe("Product category Service", () => {
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
testSuite: ({
MikroOrmWrapper,
medusaApp,
}: SuiteOptions<IProductModuleService>) => {
describe("Product category Service", () => {
let service: ProductCategoryService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let productCategories!: ProductCategory[]
beforeEach(async () => {
await TestDatabase.setupDatabase()
repositoryManager = await TestDatabase.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("productCategoryService")
})
afterEach(async () => {
await TestDatabase.clearDatabase()
beforeEach(() => {
service = medusaApp.modules["productService"].productCategoryService_
})
describe("list", () => {
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
productCategories = await createProductCategories(
testManager,
await createProductCategories(
MikroOrmWrapper.forkManager(),
productCategoriesData
)
})
@@ -239,10 +224,8 @@ describe("Product category Service", () => {
const categoryOneId = "category-1"
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
productCategories = await createProductCategories(
testManager,
await createProductCategories(
MikroOrmWrapper.forkManager(),
productCategoriesData
)
})
@@ -323,10 +306,8 @@ describe("Product category Service", () => {
describe("listAndCount", () => {
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
productCategories = await createProductCategories(
testManager,
await createProductCategories(
MikroOrmWrapper.forkManager(),
productCategoriesData
)
})
@@ -645,10 +626,8 @@ describe("Product category Service", () => {
let categories
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
categories = await createProductCategories(
testManager,
MikroOrmWrapper.forkManager(),
productCategoriesRankData
)
@@ -665,9 +644,12 @@ describe("Product category Service", () => {
name: "New Category",
})
const productCategory = await service.retrieve(productCategoryZero.id, {
const productCategory = await service.retrieve(
productCategoryZero.id,
{
select: ["name"],
})
}
)
expect(productCategory.name).toEqual("New Category")
})
@@ -802,10 +784,8 @@ describe("Product category Service", () => {
let categories
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
categories = await createProductCategories(
testManager,
MikroOrmWrapper.forkManager(),
productCategoriesRankData
)
@@ -868,4 +848,6 @@ describe("Product category Service", () => {
)
})
})
})
},
})
@@ -1,36 +1,23 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { ProductCollection } from "@models"
import { ProductCollectionService } from "@services"
import { createCollections } from "../../../__fixtures__/product"
import { TestDatabase } from "../../../utils"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { IProductModuleService } from "@medusajs/types"
jest.setTimeout(30000)
describe("Product collection Service", () => {
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
testSuite: ({
MikroOrmWrapper,
medusaApp,
}: SuiteOptions<IProductModuleService>) => {
describe("Product collection Service", () => {
let service: ProductCollectionService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let collectionsData: ProductCollection[] = []
beforeEach(async () => {
await TestDatabase.setupDatabase()
repositoryManager = await TestDatabase.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("productCollectionService")
})
afterEach(async () => {
await TestDatabase.clearDatabase()
beforeEach(() => {
service = medusaApp.modules["productService"].productCollectionService_
})
describe("list", () => {
@@ -54,9 +41,7 @@ describe("Product collection Service", () => {
]
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
collectionsData = await createCollections(testManager, data)
await createCollections(MikroOrmWrapper.forkManager(), data)
})
it("list product collections", async () => {
@@ -83,7 +68,9 @@ describe("Product collection Service", () => {
})
it("list product collections by id", async () => {
const productCollectionResults = await service.list({ id: data![0].id })
const productCollectionResults = await service.list({
id: data![0].id,
})
expect(productCollectionResults).toEqual([
expect.objectContaining({
@@ -128,14 +115,14 @@ describe("Product collection Service", () => {
]
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
collectionsData = await createCollections(testManager, data)
await createCollections(MikroOrmWrapper.forkManager(), data)
})
it("should return all collections and count", async () => {
const [productCollectionResults, count] = await service.listAndCount()
const serialized = JSON.parse(JSON.stringify(productCollectionResults))
const serialized = JSON.parse(
JSON.stringify(productCollectionResults)
)
expect(serialized).toEqual([
expect.objectContaining({
@@ -161,7 +148,9 @@ describe("Product collection Service", () => {
const [productCollectionResults, count] = await service.listAndCount({
id: data![0].id,
})
const serialized = JSON.parse(JSON.stringify(productCollectionResults))
const serialized = JSON.parse(
JSON.stringify(productCollectionResults)
)
expect(count).toEqual(1)
expect(serialized).toEqual([
@@ -182,7 +171,9 @@ describe("Product collection Service", () => {
skip: 1,
}
)
const serialized = JSON.parse(JSON.stringify(productCollectionResults))
const serialized = JSON.parse(
JSON.stringify(productCollectionResults)
)
expect(count).toEqual(4)
expect(serialized).toEqual([
@@ -202,13 +193,15 @@ describe("Product collection Service", () => {
}
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
await createCollections(testManager, [collectionData])
await createCollections(MikroOrmWrapper.forkManager(), [
collectionData,
])
})
it("should return collection for the given id", async () => {
const productCollectionResults = await service.retrieve(collectionData.id)
const productCollectionResults = await service.retrieve(
collectionData.id
)
expect(productCollectionResults).toEqual(
expect.objectContaining({
@@ -240,7 +233,9 @@ describe("Product collection Service", () => {
error = e
}
expect(error.message).toEqual("productCollection - id must be defined")
expect(error.message).toEqual(
"productCollection - id must be defined"
)
})
it("should return collection based on config select param", async () => {
@@ -251,7 +246,9 @@ describe("Product collection Service", () => {
}
)
const serialized = JSON.parse(JSON.stringify(productCollectionResults))
const serialized = JSON.parse(
JSON.stringify(productCollectionResults)
)
expect(serialized).toEqual({
id: collectionData.id,
@@ -268,7 +265,9 @@ describe("Product collection Service", () => {
}
)
const serialized = JSON.parse(JSON.stringify(productCollectionResults))
const serialized = JSON.parse(
JSON.stringify(productCollectionResults)
)
expect(serialized).toEqual({
id: collectionData.id,
@@ -286,9 +285,9 @@ describe("Product collection Service", () => {
}
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
await createCollections(testManager, [collectionData])
await createCollections(MikroOrmWrapper.forkManager(), [
collectionData,
])
})
it("should delete the product collection given an ID successfully", async () => {
@@ -310,9 +309,9 @@ describe("Product collection Service", () => {
}
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
await createCollections(testManager, [collectionData])
await createCollections(MikroOrmWrapper.forkManager(), [
collectionData,
])
})
it("should update the value of the collection successfully", async () => {
@@ -363,4 +362,6 @@ describe("Product collection Service", () => {
expect(productCollection.title).toEqual("New Collection")
})
})
})
},
})
@@ -1,44 +1,31 @@
import { MedusaModule, Modules } from "@medusajs/modules-sdk"
import { Modules } from "@medusajs/modules-sdk"
import { IProductModuleService, ProductTypes } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Product, ProductCategory } from "@models"
import { initModules } from "medusa-test-utils"
import { EventBusService } from "../../../__fixtures__/event-bus"
import { MockEventBusService } from "medusa-test-utils"
import { createProductCategories } from "../../../__fixtures__/product-category"
import { productCategoriesRankData } from "../../../__fixtures__/product-category/data"
import { TestDatabase, getInitModuleConfig } from "../../../utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
describe("ProductModuleService product categories", () => {
let service: IProductModuleService
let testManager: SqlEntityManager
jest.setTimeout(30000)
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
injectedDependencies: {
eventBusModuleService: new MockEventBusService(),
},
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IProductModuleService>) => {
describe("ProductModuleService product categories", () => {
let productOne: Product
let productTwo: Product
let productCategoryOne: ProductCategory
let productCategoryTwo: ProductCategory
let productCategories: ProductCategory[]
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await TestDatabase.setupDatabase()
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
productOne = testManager.create(Product, {
id: "product-1",
@@ -73,11 +60,13 @@ describe("ProductModuleService product categories", () => {
productCategoryOne = productCategories[0]
productCategoryTwo = productCategories[1]
await testManager.persistAndFlush([productCategoryOne, productCategoryTwo])
await testManager.persistAndFlush([
productCategoryOne,
productCategoryTwo,
])
})
afterEach(async () => {
await TestDatabase.clearDatabase()
jest.clearAllMocks()
})
@@ -180,7 +169,10 @@ describe("ProductModuleService product categories", () => {
expect(results[1]).toEqual(2)
results = await service.listAndCountCategories({}, { take: 1, skip: 1 })
results = await service.listAndCountCategories(
{},
{ take: 1, skip: 1 }
)
expect(results[1]).toEqual(2)
expect(results[0]).toEqual([
@@ -291,7 +283,7 @@ describe("ProductModuleService product categories", () => {
})
it("should emit events through event bus", async () => {
const eventBusSpy = jest.spyOn(EventBusService.prototype, "emit")
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
const category = await service.createCategory({
name: "New Category",
@@ -366,7 +358,7 @@ describe("ProductModuleService product categories", () => {
let categories
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
categories = await createProductCategories(
testManager,
@@ -382,7 +374,7 @@ describe("ProductModuleService product categories", () => {
})
it("should emit events through event bus", async () => {
const eventBusSpy = jest.spyOn(EventBusService.prototype, "emit")
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
await service.updateCategory(productCategoryZero.id, {
name: "New Category",
})
@@ -538,7 +530,7 @@ describe("ProductModuleService product categories", () => {
let categories
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
categories = await createProductCategories(
testManager,
@@ -551,7 +543,7 @@ describe("ProductModuleService product categories", () => {
})
it("should emit events through event bus", async () => {
const eventBusSpy = jest.spyOn(EventBusService.prototype, "emit")
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
await service.deleteCategory(productCategoryOne.id)
expect(eventBusSpy).toHaveBeenCalledTimes(1)
@@ -614,4 +606,6 @@ describe("ProductModuleService product categories", () => {
)
})
})
})
},
})
@@ -1,43 +1,30 @@
import { IProductModuleService, ProductTypes } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Product, ProductCollection } from "@models"
import { EventBusService } from "../../../__fixtures__/event-bus"
import { MockEventBusService } from "medusa-test-utils"
import { createCollections } from "../../../__fixtures__/product"
import { getInitModuleConfig, TestDatabase } from "../../../utils"
import { MedusaModule, Modules } from "@medusajs/modules-sdk"
import { initModules } from "medusa-test-utils"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
describe("ProductModuleService product collections", () => {
let service: IProductModuleService
let testManager: SqlEntityManager
jest.setTimeout(30000)
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
injectedDependencies: {
eventBusModuleService: new MockEventBusService(),
},
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IProductModuleService>) => {
describe("ProductModuleService product collections", () => {
let productOne: Product
let productTwo: Product
let productCollectionOne: ProductCollection
let productCollectionTwo: ProductCollection
let productCollections: ProductCollection[]
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await TestDatabase.setupDatabase()
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
productOne = testManager.create(Product, {
id: "product-1",
@@ -74,7 +61,6 @@ describe("ProductModuleService product collections", () => {
})
afterEach(async () => {
await TestDatabase.clearDatabase()
jest.clearAllMocks()
})
@@ -177,7 +163,10 @@ describe("ProductModuleService product collections", () => {
expect(results[1]).toEqual(2)
results = await service.listAndCountCollections({}, { take: 1, skip: 1 })
results = await service.listAndCountCollections(
{},
{ take: 1, skip: 1 }
)
expect(results[1]).toEqual(2)
expect(results[0]).toEqual([
@@ -216,7 +205,9 @@ describe("ProductModuleService product collections", () => {
describe("retrieveCollection", () => {
it("should return the requested collection", async () => {
const result = await service.retrieveCollection(productCollectionOne.id)
const result = await service.retrieveCollection(
productCollectionOne.id
)
expect(result).toEqual(
expect.objectContaining({
@@ -227,10 +218,13 @@ describe("ProductModuleService product collections", () => {
})
it("should return requested attributes when requested through config", async () => {
const result = await service.retrieveCollection(productCollectionOne.id, {
const result = await service.retrieveCollection(
productCollectionOne.id,
{
select: ["id", "title", "products.title"],
relations: ["products"],
})
}
)
expect(result).toEqual(
expect.objectContaining({
@@ -275,7 +269,7 @@ describe("ProductModuleService product collections", () => {
})
it("should emit events through event bus", async () => {
const eventBusSpy = jest.spyOn(EventBusService.prototype, "emit")
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
await service.deleteCollections([collectionId])
expect(eventBusSpy).toHaveBeenCalledTimes(1)
@@ -292,7 +286,7 @@ describe("ProductModuleService product collections", () => {
const collectionId = "test-1"
it("should emit events through event bus", async () => {
const eventBusSpy = jest.spyOn(EventBusService.prototype, "emit")
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
await service.upsertCollections([
{
@@ -318,7 +312,9 @@ describe("ProductModuleService product collections", () => {
},
])
const productCollection = await service.retrieveCollection(collectionId)
const productCollection = await service.retrieveCollection(
collectionId
)
expect(productCollection.title).toEqual("New Collection")
})
@@ -331,10 +327,13 @@ describe("ProductModuleService product collections", () => {
},
])
const productCollection = await service.retrieveCollection(collectionId, {
const productCollection = await service.retrieveCollection(
collectionId,
{
select: ["products.id"],
relations: ["products"],
})
}
)
expect(productCollection.products).toHaveLength(2)
expect(productCollection).toEqual(
@@ -422,7 +421,7 @@ describe("ProductModuleService product collections", () => {
})
it("should emit events through event bus", async () => {
const eventBusSpy = jest.spyOn(EventBusService.prototype, "emit")
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
const collections = await service.createCollections([
{
@@ -439,4 +438,6 @@ describe("ProductModuleService product collections", () => {
])
})
})
})
},
})
@@ -1,40 +1,24 @@
import { IProductModuleService, ProductTypes } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Product, ProductOption } from "@models"
import { getInitModuleConfig, TestDatabase } from "../../../utils"
import { MedusaModule, Modules } from "@medusajs/modules-sdk"
import { initModules } from "medusa-test-utils"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
describe("ProductModuleService product options", () => {
let service: IProductModuleService
let testManager: SqlEntityManager
jest.setTimeout(30000)
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IProductModuleService>) => {
describe("ProductModuleService product options", () => {
let optionOne: ProductOption
let optionTwo: ProductOption
let productOne: Product
let productTwo: Product
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await TestDatabase.setupDatabase()
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
productOne = testManager.create(Product, {
id: "product-1",
title: "product 1",
@@ -62,10 +46,6 @@ describe("ProductModuleService product options", () => {
await testManager.persistAndFlush([optionOne, optionTwo])
})
afterEach(async () => {
await TestDatabase.clearDatabase()
})
describe("listOptions", () => {
it("should return options and count queried by ID", async () => {
const options = await service.listOptions({
@@ -322,4 +302,6 @@ describe("ProductModuleService product options", () => {
)
})
})
})
},
})
@@ -1,40 +1,24 @@
import { MedusaModule, Modules } from "@medusajs/modules-sdk"
import { Modules } from "@medusajs/modules-sdk"
import { IProductModuleService, ProductTypes } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Product, ProductTag } from "@models"
import { initModules } from "medusa-test-utils"
import { TestDatabase, getInitModuleConfig } from "../../../utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
describe("ProductModuleService product tags", () => {
let service: IProductModuleService
let testManager: SqlEntityManager
jest.setTimeout(30000)
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IProductModuleService>) => {
describe("ProductModuleService product tags", () => {
let tagOne: ProductTag
let tagTwo: ProductTag
let productOne: Product
let productTwo: Product
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await TestDatabase.setupDatabase()
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
productOne = testManager.create(Product, {
id: "product-1",
title: "product 1",
@@ -62,10 +46,6 @@ describe("ProductModuleService product tags", () => {
await testManager.persistAndFlush([tagOne, tagTwo])
})
afterEach(async () => {
await TestDatabase.clearDatabase()
})
describe("listTags", () => {
it("should return tags and count queried by ID", async () => {
const tags = await service.listTags({
@@ -163,7 +143,10 @@ describe("ProductModuleService product tags", () => {
;[tags, count] = await service.listAndCountTags({}, { take: 1 })
expect(count).toEqual(2)
;[tags, count] = await service.listAndCountTags({}, { take: 1, skip: 1 })
;[tags, count] = await service.listAndCountTags(
{},
{ take: 1, skip: 1 }
)
expect(count).toEqual(2)
expect(tags).toEqual([
@@ -310,4 +293,6 @@ describe("ProductModuleService product tags", () => {
expect(productTag[0]?.value).toEqual("UK")
})
})
})
},
})
@@ -1,38 +1,22 @@
import { MedusaModule, Modules } from "@medusajs/modules-sdk"
import { Modules } from "@medusajs/modules-sdk"
import { IProductModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { ProductType } from "@models"
import { initModules } from "medusa-test-utils"
import { getInitModuleConfig, TestDatabase } from "../../../utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
describe("ProductModuleService product types", () => {
let service: IProductModuleService
let testManager: SqlEntityManager
jest.setTimeout(30000)
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IProductModuleService>) => {
describe("ProductModuleService product types", () => {
let typeOne: ProductType
let typeTwo: ProductType
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await TestDatabase.setupDatabase()
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
typeOne = testManager.create(ProductType, {
id: "type-1",
@@ -47,10 +31,6 @@ describe("ProductModuleService product types", () => {
await testManager.persistAndFlush([typeOne, typeTwo])
})
afterEach(async () => {
await TestDatabase.clearDatabase()
})
describe("listTypes", () => {
it("should return types and count queried by ID", async () => {
const types = await service.listTypes({
@@ -278,4 +258,6 @@ describe("ProductModuleService product types", () => {
expect(productType[0]?.value).toEqual("UK")
})
})
})
},
})
@@ -1,39 +1,25 @@
import { MedusaModule, Modules } from "@medusajs/modules-sdk"
import { Modules } from "@medusajs/modules-sdk"
import { IProductModuleService, ProductTypes } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Product, ProductVariant } from "@models"
import { initModules } from "medusa-test-utils"
import { TestDatabase, getInitModuleConfig } from "../../../utils"
describe("ProductModuleService product variants", () => {
let service: IProductModuleService
let testManager: SqlEntityManager
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IProductModuleService>) => {
describe("ProductModuleService product variants", () => {
let variantOne: ProductVariant
let variantTwo: ProductVariant
let productOne: Product
let productTwo: Product
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
await TestDatabase.setupDatabase()
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
productOne = testManager.create(Product, {
id: "product-1",
@@ -64,10 +50,6 @@ describe("ProductModuleService product variants", () => {
await testManager.persistAndFlush([variantOne, variantTwo])
})
afterEach(async () => {
await TestDatabase.clearDatabase()
})
describe("listAndCountVariants", () => {
it("should return variants and count queried by ID", async () => {
const results = await service.listAndCountVariants({
@@ -183,4 +165,6 @@ describe("ProductModuleService product variants", () => {
)
})
})
})
},
})
@@ -1,4 +1,4 @@
import { MedusaModule, Modules } from "@medusajs/modules-sdk"
import { Modules } from "@medusajs/modules-sdk"
import { IProductModuleService, ProductTypes } from "@medusajs/types"
import { kebabCase } from "@medusajs/utils"
import {
@@ -9,28 +9,25 @@ import {
ProductVariant,
} from "@models"
import { initModules } from "medusa-test-utils"
import { initialize } from "../../../../src"
import { EventBusService } from "../../../__fixtures__/event-bus"
import { MockEventBusService } from "medusa-test-utils"
import { createCollections, createTypes } from "../../../__fixtures__/product"
import { createProductCategories } from "../../../__fixtures__/product-category"
import { buildProductAndRelationsData } from "../../../__fixtures__/product/data/create-product"
import { DB_URL, TestDatabase, getInitModuleConfig } from "../../../utils"
import { UpdateProductInput } from "../../../../src/types/services/product"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
const beforeEach_ = async () => {
await TestDatabase.setupDatabase()
return await TestDatabase.forkManager()
}
const afterEach_ = async () => {
await TestDatabase.clearDatabase()
jest.clearAllMocks()
}
describe("ProductModuleService products", function () {
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
injectedDependencies: {
eventBusModuleService: new MockEventBusService(),
},
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IProductModuleService>) => {
describe("ProductModuleService products", function () {
let productCollectionOne: ProductCollection
let productCollectionTwo: ProductCollection
@@ -45,15 +42,16 @@ describe("ProductModuleService products", function () {
},
]
afterEach(() => {
jest.clearAllMocks()
})
describe("update", function () {
let module: IProductModuleService
let productOne: Product
let productTwo: Product
let productCategoryOne: ProductCategory
let productCategoryTwo: ProductCategory
let variantOne: ProductVariant
let variantTwo: ProductVariant
let variantThree: ProductVariant
let productTypeOne: ProductType
let productTypeTwo: ProductType
let images = ["image-1"]
@@ -87,26 +85,8 @@ describe("ProductModuleService products", function () {
},
]
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
MedusaModule.clearInstances()
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
module = medusaApp.modules[Modules.PRODUCT]
shutdownFunc = shutdown
})
afterAll(async () => {
await shutdownFunc()
})
beforeEach(async () => {
const testManager = await beforeEach_()
const testManager = MikroOrmWrapper.forkManager()
const collections = await createCollections(
testManager,
@@ -144,7 +124,7 @@ describe("ProductModuleService products", function () {
tags: tagsData,
})
variantOne = testManager.create(ProductVariant, {
testManager.create(ProductVariant, {
id: "variant-1",
title: "variant 1",
inventory_quantity: 10,
@@ -158,7 +138,7 @@ describe("ProductModuleService products", function () {
product: productTwo,
})
variantThree = testManager.create(ProductVariant, {
testManager.create(ProductVariant, {
id: "variant-3",
title: "variant 3",
inventory_quantity: 10,
@@ -168,8 +148,6 @@ describe("ProductModuleService products", function () {
await testManager.persistAndFlush([productOne, productTwo])
})
afterEach(afterEach_)
it("should update a product and upsert relations that are not created yet", async () => {
const data = buildProductAndRelationsData({
images,
@@ -178,7 +156,7 @@ describe("ProductModuleService products", function () {
const variantTitle = data.variants[0].title
const productBefore = (await module.retrieve(productOne.id, {
const productBefore = (await service.retrieve(productOne.id, {
relations: [
"images",
"variants",
@@ -191,17 +169,24 @@ describe("ProductModuleService products", function () {
})) as unknown as UpdateProductInput
productBefore.title = "updated title"
productBefore.variants = [...productBefore.variants!, ...data.variants]
productBefore.variants = [
...productBefore.variants!,
...data.variants,
]
productBefore.type = { value: "new-type" }
productBefore.options = data.options
// TODO: Change test (this one and below) to not require setting product ID here.
productBefore.options = data.options.map((o) => ({
...o,
product_id: productBefore.id,
}))
productBefore.images = data.images
productBefore.thumbnail = data.thumbnail
productBefore.tags = data.tags
const updatedProducts = await module.upsert([productBefore])
const updatedProducts = await service.upsert([productBefore])
expect(updatedProducts).toHaveLength(1)
const product = await module.retrieve(productBefore.id, {
const product = await service.retrieve(productBefore.id, {
relations: [
"images",
"variants",
@@ -282,7 +267,7 @@ describe("ProductModuleService products", function () {
})
it("should emit events through event bus", async () => {
const eventBusSpy = jest.spyOn(EventBusService.prototype, "emit")
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
const data = buildProductAndRelationsData({
images,
thumbnail: images[0],
@@ -290,11 +275,15 @@ describe("ProductModuleService products", function () {
const updateData = {
...data,
options: data.options.map((o) => ({
...o,
product_id: productOne.id,
})),
id: productOne.id,
title: "updated title",
}
await module.upsert([updateData])
await service.upsert([updateData])
expect(eventBusSpy).toHaveBeenCalledTimes(1)
expect(eventBusSpy).toHaveBeenCalledWith([
@@ -317,9 +306,9 @@ describe("ProductModuleService products", function () {
type_id: productTypeOne.id,
}
await module.upsert([updateData])
await service.upsert([updateData])
const product = await module.retrieve(updateData.id, {
const product = await service.retrieve(updateData.id, {
relations: ["categories", "collection", "type"],
})
@@ -350,9 +339,9 @@ describe("ProductModuleService products", function () {
},
}
await module.upsert([updateData])
await service.upsert([updateData])
let product = await module.retrieve(updateData.id, {
let product = await service.retrieve(updateData.id, {
relations: ["type"],
})
@@ -373,9 +362,9 @@ describe("ProductModuleService products", function () {
},
}
await module.upsert([updateData])
await service.upsert([updateData])
product = await module.retrieve(updateData.id, {
product = await service.retrieve(updateData.id, {
relations: ["type"],
})
@@ -407,9 +396,9 @@ describe("ProductModuleService products", function () {
tags: [newTagData],
}
await module.upsert([updateData])
await service.upsert([updateData])
const product = await module.retrieve(updateData.id, {
const product = await service.retrieve(updateData.id, {
relations: ["categories", "collection", "tags", "type"],
})
@@ -446,9 +435,9 @@ describe("ProductModuleService products", function () {
tags: [],
}
await module.upsert([updateData])
await service.upsert([updateData])
const product = await module.retrieve(updateData.id, {
const product = await service.retrieve(updateData.id, {
relations: ["categories", "collection", "tags"],
})
@@ -471,7 +460,7 @@ describe("ProductModuleService products", function () {
}
try {
await module.upsert([updateData])
await service.upsert([updateData])
} catch (e) {
error = e.message
}
@@ -494,9 +483,9 @@ describe("ProductModuleService products", function () {
],
}
await module.upsert([updateData])
await service.upsert([updateData])
const product = await module.retrieve(updateData.id, {
const product = await service.retrieve(updateData.id, {
relations: ["variants"],
})
@@ -536,12 +525,12 @@ describe("ProductModuleService products", function () {
}
try {
await module.upsert([updateData])
await service.upsert([updateData])
} catch (e) {
error = e
}
await module.retrieve(updateData.id, {
await service.retrieve(updateData.id, {
relations: ["variants"],
})
@@ -552,40 +541,16 @@ describe("ProductModuleService products", function () {
})
describe("create", function () {
let module: IProductModuleService
let images = ["image-1"]
let eventBus
beforeEach(async () => {
await beforeEach_()
MedusaModule.clearInstances()
eventBus = new EventBusService()
module = await initialize(
{
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_PRODUCT_DB_SCHEMA,
},
},
{
eventBusModuleService: eventBus,
}
)
})
afterEach(afterEach_)
it("should create a product", async () => {
const data = buildProductAndRelationsData({
images,
thumbnail: images[0],
})
const productsCreated = await module.create([data])
const productsCreated = await service.create([data])
const products = await module.list(
const products = await service.list(
{ id: productsCreated[0].id },
{
relations: [
@@ -669,14 +634,13 @@ describe("ProductModuleService products", function () {
})
it("should emit events through eventBus", async () => {
const eventBusSpy = jest.spyOn(EventBusService.prototype, "emit")
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
const data = buildProductAndRelationsData({
images,
thumbnail: images[0],
})
const products = await module.create([data])
const products = await service.create([data])
expect(eventBusSpy).toHaveBeenCalledTimes(1)
expect(eventBusSpy).toHaveBeenCalledWith([
{
@@ -688,42 +652,18 @@ describe("ProductModuleService products", function () {
})
describe("softDelete", function () {
let module: IProductModuleService
let images = ["image-1"]
let eventBus
beforeEach(async () => {
await beforeEach_()
MedusaModule.clearInstances()
eventBus = new EventBusService()
module = await initialize(
{
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_PRODUCT_DB_SCHEMA,
},
},
{
eventBusModuleService: eventBus,
}
)
})
afterEach(afterEach_)
it("should soft delete a product and its cascaded relations", async () => {
const data = buildProductAndRelationsData({
images,
thumbnail: images[0],
})
const products = await module.create([data])
const products = await service.create([data])
await module.softDelete([products[0].id])
await service.softDelete([products[0].id])
const deletedProducts = await module.list(
const deletedProducts = await service.list(
{ id: products[0].id },
{
relations: [
@@ -770,11 +710,11 @@ describe("ProductModuleService products", function () {
thumbnail: images[0],
})
const products = await module.create([data])
const products = await service.create([data])
await module.softDelete([products[0].id])
await service.softDelete([products[0].id])
const softDeleted = await module.list({
const softDeleted = await service.list({
deleted_at: { $gt: "01-01-2022" },
})
@@ -782,15 +722,15 @@ describe("ProductModuleService products", function () {
})
it("should emit events through eventBus", async () => {
const eventBusSpy = jest.spyOn(EventBusService.prototype, "emit")
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
const data = buildProductAndRelationsData({
images,
thumbnail: images[0],
})
const products = await module.create([data])
const products = await service.create([data])
await module.softDelete([products[0].id])
await service.softDelete([products[0].id])
expect(eventBusSpy).toHaveBeenCalledWith([
{
@@ -802,40 +742,24 @@ describe("ProductModuleService products", function () {
})
describe("restore", function () {
let module: IProductModuleService
let images = ["image-1"]
beforeEach(async () => {
await beforeEach_()
MedusaModule.clearInstances()
module = await initialize({
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_PRODUCT_DB_SCHEMA,
},
})
})
afterEach(afterEach_)
it("should restore a soft deleted product and its cascaded relations", async () => {
const data = buildProductAndRelationsData({
images,
thumbnail: images[0],
})
const products = await module.create([data])
const products = await service.create([data])
let retrievedProducts = await module.list({ id: products[0].id })
let retrievedProducts = await service.list({ id: products[0].id })
expect(retrievedProducts).toHaveLength(1)
expect(retrievedProducts[0].deleted_at).toBeNull()
await module.softDelete([products[0].id])
await service.softDelete([products[0].id])
retrievedProducts = await module.list(
retrievedProducts = await service.list(
{ id: products[0].id },
{
withDeleted: true,
@@ -845,9 +769,9 @@ describe("ProductModuleService products", function () {
expect(retrievedProducts).toHaveLength(1)
expect(retrievedProducts[0].deleted_at).not.toBeNull()
await module.restore([products[0].id])
await service.restore([products[0].id])
const deletedProducts = await module.list(
const deletedProducts = await service.list(
{ id: products[0].id },
{
relations: [
@@ -891,29 +815,15 @@ describe("ProductModuleService products", function () {
})
describe("list", function () {
let module: IProductModuleService
let collections: ProductCollection
beforeEach(async () => {
const testManager = await beforeEach_()
const collections = await createCollections(
testManager,
MikroOrmWrapper.forkManager(),
productCollectionsData
)
productCollectionOne = collections[0]
productCollectionTwo = collections[1]
MedusaModule.clearInstances()
module = await initialize({
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_PRODUCT_DB_SCHEMA,
},
})
const productOneData = buildProductAndRelationsData({
collection_id: productCollectionOne.id,
})
@@ -922,13 +832,11 @@ describe("ProductModuleService products", function () {
collection_id: productCollectionTwo.id,
})
await module.create([productOneData, productTwoData])
await service.create([productOneData, productTwoData])
})
afterEach(afterEach_)
it("should return a list of products scoped by collection id", async () => {
const productsWithCollectionOne = await module.list(
const productsWithCollectionOne = await service.list(
{ collection_id: productCollectionOne.id },
{
relations: ["collection"],
@@ -947,7 +855,7 @@ describe("ProductModuleService products", function () {
})
it("should returns empty array when querying for a collection that doesnt exist", async () => {
const products = await module.list(
const products = await service.list(
{
categories: { id: ["collection-doesnt-exist-id"] },
},
@@ -960,4 +868,6 @@ describe("ProductModuleService products", function () {
expect(products).toEqual([])
})
})
})
},
})
@@ -1,24 +1,30 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { ProductOptionService } from "@services"
import { Product } from "@models"
import { TestDatabase } from "../../../utils"
import { createOptions } from "../../../__fixtures__/product"
import { ProductTypes } from "@medusajs/types"
import { asValue } from "awilix"
import { createMedusaContainer } from "@medusajs/utils"
import ContainerLoader from "../../../../src/loaders/container"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { IProductModuleService } from "@medusajs/types"
jest.setTimeout(30000)
describe("ProductOption Service", () => {
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
testSuite: ({
MikroOrmWrapper,
medusaApp,
}: SuiteOptions<IProductModuleService>) => {
describe("ProductOption Service", () => {
let service: ProductOptionService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
beforeEach(() => {
service = medusaApp.modules["productService"].productOptionService_
})
let productOne: Product
let productTwo: Product
let data!: Product[]
const productOneData = {
id: "product-1",
@@ -33,21 +39,11 @@ describe("ProductOption Service", () => {
}
beforeEach(async () => {
await TestDatabase.setupDatabase()
repositoryManager = await TestDatabase.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("productOptionService")
testManager = await TestDatabase.forkManager()
const testManager = MikroOrmWrapper.forkManager()
productOne = testManager.create(Product, productOneData)
productTwo = testManager.create(Product, productTwoData)
data = await createOptions(testManager, [
await createOptions(testManager, [
{
id: "option-1",
title: "Option 1",
@@ -61,10 +57,6 @@ describe("ProductOption Service", () => {
])
})
afterEach(async () => {
await TestDatabase.clearDatabase()
})
describe("list", () => {
it("list product option", async () => {
const optionResults = await service.list()
@@ -373,4 +365,6 @@ describe("ProductOption Service", () => {
)
})
})
})
},
})
@@ -1,22 +1,27 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Product } from "@models"
import { ProductTagService } from "@services"
import { ProductTypes } from "@medusajs/types"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
import { createProductAndTags } from "../../../__fixtures__/product"
import { TestDatabase } from "../../../utils"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { IProductModuleService } from "@medusajs/types"
jest.setTimeout(30000)
describe("ProductTag Service", () => {
let service: ProductTagService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
testSuite: ({
MikroOrmWrapper,
medusaApp,
}: SuiteOptions<IProductModuleService>) => {
describe("ProductTag Service", () => {
let data!: Product[]
let service: ProductTagService
beforeEach(() => {
service = medusaApp.modules["productService"].productTagService_
})
const productsData = [
{
@@ -52,23 +57,10 @@ describe("ProductTag Service", () => {
]
beforeEach(async () => {
await TestDatabase.setupDatabase()
repositoryManager = await TestDatabase.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("productTagService")
testManager = await TestDatabase.forkManager()
data = await createProductAndTags(testManager, productsData)
})
afterEach(async () => {
await TestDatabase.clearDatabase()
data = await createProductAndTags(
MikroOrmWrapper.forkManager(),
productsData
)
})
describe("list", () => {
@@ -338,4 +330,6 @@ describe("ProductTag Service", () => {
expect(productTag.value).toEqual("UK")
})
})
})
},
})
@@ -1,22 +1,27 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import ContainerLoader from "../../../../src/loaders/container"
import { ProductTypeService } from "@services"
import { Product } from "@models"
import { TestDatabase } from "../../../utils"
import { createProductAndTypes } from "../../../__fixtures__/product"
import { ProductTypes } from "@medusajs/types"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { IProductModuleService } from "@medusajs/types"
jest.setTimeout(30000)
describe("ProductType Service", () => {
let service: ProductTypeService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
testSuite: ({
MikroOrmWrapper,
medusaApp,
}: SuiteOptions<IProductModuleService>) => {
describe("ProductType Service", () => {
let data!: Product[]
let service: ProductTypeService
beforeEach(() => {
service = medusaApp.modules["productService"].productTypeService_
})
const productsData = [
{
@@ -40,25 +45,11 @@ describe("ProductType Service", () => {
]
beforeEach(async () => {
await TestDatabase.setupDatabase()
repositoryManager = await TestDatabase.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("productTypeService")
testManager = await TestDatabase.forkManager()
data = await createProductAndTypes(testManager, productsData)
data = await createProductAndTypes(
MikroOrmWrapper.forkManager(),
productsData
)
})
afterEach(async () => {
await TestDatabase.clearDatabase()
})
describe("list", () => {
it("list product type", async () => {
const typeResults = await service.list()
@@ -281,4 +272,6 @@ describe("ProductType Service", () => {
expect(productType.value).toEqual("UK")
})
})
})
},
})
@@ -1,12 +1,8 @@
import { ProductOption } from "@medusajs/client-types"
import { ProductTypes } from "@medusajs/types"
import { createMedusaContainer } from "@medusajs/utils"
import { Collection } from "@mikro-orm/core"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Product, ProductTag, ProductVariant } from "@models"
import { ProductVariantService } from "@services"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
import {
createOptions,
createProductAndTags,
@@ -14,37 +10,33 @@ import {
} from "../../../__fixtures__/product"
import { productsData, variantsData } from "../../../__fixtures__/product/data"
import { buildProductVariantOnlyData } from "../../../__fixtures__/variant/data/create-variant"
import { TestDatabase } from "../../../utils"
// TODO: fix tests
describe.skip("ProductVariant Service", () => {
let service: ProductVariantService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { IProductModuleService } from "@medusajs/types"
jest.setTimeout(30000)
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
testSuite: ({
MikroOrmWrapper,
medusaApp,
}: SuiteOptions<IProductModuleService>) => {
describe.skip("ProductVariant Service", () => {
let variantOne: ProductVariant
let variantTwo: ProductVariant
let productOne: Product
const productVariantTestOne = "test-1"
let service: ProductVariantService
beforeEach(async () => {
await TestDatabase.setupDatabase()
repositoryManager = await TestDatabase.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("productVariantService")
})
afterEach(async () => {
await TestDatabase.clearDatabase()
beforeEach(() => {
service = medusaApp.modules["productService"].productVariantService_
})
describe("list", () => {
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
productOne = testManager.create(Product, {
id: "product-1",
@@ -141,7 +133,7 @@ describe.skip("ProductVariant Service", () => {
let options: ProductOption[]
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
products = (await createProductAndTags(
testManager,
@@ -158,8 +150,16 @@ describe.skip("ProductVariant Service", () => {
title: "size",
product: products[0],
values: [
{ id: "value-1", value: "XS", variant: products[0].variants[0] },
{ id: "value-1", value: "XL", variant: products[0].variants[0] },
{
id: "value-1",
value: "XS",
variant: products[0].variants[0],
},
{
id: "value-1",
value: "XL",
variant: products[0].variants[0],
},
],
},
{
@@ -193,7 +193,7 @@ describe.skip("ProductVariant Service", () => {
let productOptions!: ProductOption[]
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
products = (await createProductAndTags(
testManager,
@@ -249,7 +249,7 @@ describe.skip("ProductVariant Service", () => {
describe("retrieve", () => {
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
const testManager = await MikroOrmWrapper.forkManager()
productOne = testManager.create(Product, {
id: "product-1",
@@ -323,4 +323,6 @@ describe.skip("ProductVariant Service", () => {
expect(error.message).toEqual("productVariant - id must be defined")
})
})
})
},
})
@@ -1,10 +1,4 @@
import {
Image,
Product,
ProductCategory,
ProductCollection,
ProductVariant,
} from "@models"
import { Image, Product, ProductCategory, ProductCollection } from "@models"
import {
assignCategoriesToProduct,
buildProductOnlyData,
@@ -19,47 +13,41 @@ import {
productsData,
variantsData,
} from "../../../__fixtures__/product/data"
import { ProductDTO, ProductTypes } from "@medusajs/types"
import { createMedusaContainer, kebabCase } from "@medusajs/utils"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { ProductService } from "@services"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
import {
IProductModuleService,
ProductDTO,
ProductTypes,
} from "@medusajs/types"
import { kebabCase } from "@medusajs/utils"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { createProductCategories } from "../../../__fixtures__/product-category"
import { TestDatabase } from "../../../utils"
import { Modules } from "@medusajs/modules-sdk"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
describe("Product Service", () => {
moduleIntegrationTestRunner({
moduleName: Modules.PRODUCT,
testSuite: ({
MikroOrmWrapper,
medusaApp,
}: SuiteOptions<IProductModuleService>) => {
let service: ProductService
beforeEach(() => {
service = medusaApp.modules["productService"].productService_
})
describe("Product Service", () => {
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let products!: Product[]
let productOne: Product
let variants!: ProductVariant[]
let categories!: ProductCategory[]
let collections!: ProductCollection[]
beforeEach(async () => {
await TestDatabase.setupDatabase()
repositoryManager = await TestDatabase.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("productService")
})
afterEach(async () => {
await TestDatabase.clearDatabase()
})
describe("retrieve", () => {
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
testManager = await MikroOrmWrapper.forkManager()
productOne = testManager.create(Product, {
id: "product-1",
title: "product 1",
@@ -110,7 +98,7 @@ describe("Product Service", () => {
let images: Image[] = []
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
testManager = await MikroOrmWrapper.forkManager()
images = await createImages(testManager, ["image-1"])
})
@@ -150,7 +138,7 @@ describe("Product Service", () => {
let images: Image[] = []
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
testManager = await MikroOrmWrapper.forkManager()
images = await createImages(testManager, ["image-1", "image-2"])
productOne = testManager.create(Product, {
@@ -250,9 +238,12 @@ describe("Product Service", () => {
let product
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
testManager = await MikroOrmWrapper.forkManager()
const products = await createProductAndTags(testManager, productsData)
const products = await createProductAndTags(
testManager,
productsData
)
product = products[1]
await service.softDelete([products[0].id])
@@ -274,7 +265,7 @@ describe("Product Service", () => {
describe("relation: tags", () => {
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
testManager = await MikroOrmWrapper.forkManager()
products = await createProductAndTags(testManager, productsData)
})
@@ -334,11 +325,14 @@ describe("Product Service", () => {
let workingCategory: ProductCategory
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
testManager = await MikroOrmWrapper.forkManager()
products = await createProductAndTags(testManager, productsData)
workingProduct = products.find((p) => p.id === "test-1") as Product
categories = await createProductCategories(testManager, categoriesData)
categories = await createProductCategories(
testManager,
categoriesData
)
workingCategory = (await testManager.findOne(
ProductCategory,
"category-1"
@@ -438,8 +432,8 @@ describe("Product Service", () => {
]
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
collections = await createCollections(testManager, collectionData)
testManager = await MikroOrmWrapper.forkManager()
await createCollections(testManager, collectionData)
workingCollection = (await testManager.findOne(
ProductCollection,
"test-1"
@@ -464,7 +458,9 @@ describe("Product Service", () => {
])
workingProduct = products.find((p) => p.id === "test-1") as Product
workingProductTwo = products.find((p) => p.id === "test-2") as Product
workingProductTwo = products.find(
(p) => p.id === "test-2"
) as Product
})
it("should filter by collection relation and scope fields", async () => {
@@ -548,10 +544,10 @@ describe("Product Service", () => {
describe("relation: variants", () => {
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
testManager = await MikroOrmWrapper.forkManager()
products = await createProductAndTags(testManager, productsData)
variants = await createProductVariants(testManager, variantsData)
await createProductVariants(testManager, variantsData)
})
it("should filter by id and including relations", async () => {
@@ -598,7 +594,7 @@ describe("Product Service", () => {
let images: Image[] = []
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
testManager = await MikroOrmWrapper.forkManager()
images = await createImages(testManager, ["image-1"])
})
@@ -633,7 +629,7 @@ describe("Product Service", () => {
let images: Image[] = []
beforeEach(async () => {
testManager = await TestDatabase.forkManager()
testManager = await MikroOrmWrapper.forkManager()
images = await createImages(testManager, ["image-1"])
})
@@ -653,4 +649,6 @@ describe("Product Service", () => {
expect(restoreProducts[0].deleted_at).toBeNull()
})
})
})
},
})
@@ -1,6 +0,0 @@
if (typeof process.env.DB_TEMP_NAME === "undefined") {
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
process.env.DB_TEMP_NAME = `medusa-integration-${tempName}`
}
process.env.MEDUSA_PRODUCT_DB_SCHEMA = "medusa-product"
@@ -1,22 +0,0 @@
const { dropDatabase } = require("pg-god")
const DB_HOST = process.env.DB_HOST ?? "localhost"
const DB_USERNAME = process.env.DB_USERNAME ?? "postgres"
const DB_PASSWORD = process.env.DB_PASSWORD ?? ""
const DB_NAME = process.env.DB_TEMP_NAME
const pgGodCredentials = {
user: DB_USERNAME,
password: DB_PASSWORD,
host: DB_HOST,
}
afterAll(async () => {
try {
await dropDatabase({ databaseName: DB_NAME }, pgGodCredentials)
} catch (e) {
console.error(
`This might fail if it is run during the unit tests since there is no database to drop. Otherwise, please check what is the issue. ${e.message}`
)
}
})
@@ -1,6 +0,0 @@
import { ModuleServiceInitializeOptions } from "@medusajs/types"
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
schema: "public",
clientUrl: "medusa-products-test",
}
@@ -1,95 +0,0 @@
import { TSMigrationGenerator } from "@mikro-orm/migrations"
import { MikroORM, Options, SqlEntityManager } from "@mikro-orm/postgresql"
import * as ProductModels from "@models"
import * as process from "process"
const DB_HOST = process.env.DB_HOST ?? "localhost"
const DB_USERNAME = process.env.DB_USERNAME ?? ""
const DB_PASSWORD = process.env.DB_PASSWORD
const DB_NAME = process.env.DB_TEMP_NAME
export const DB_URL = `postgres://${DB_USERNAME}${
DB_PASSWORD ? `:${DB_PASSWORD}` : ""
}@${DB_HOST}/${DB_NAME}`
const ORMConfig: Options = {
type: "postgresql",
clientUrl: DB_URL,
entities: Object.values(ProductModels),
schema: process.env.MEDUSA_PRODUCT_DB_SCHEMA,
debug: false,
migrations: {
path: "../../src/migrations",
pathTs: "../../src/migrations",
glob: "!(*.d).{js,ts}",
silent: true,
dropTables: true,
transactional: true,
allOrNothing: true,
safe: false,
generator: TSMigrationGenerator,
},
}
interface TestDatabase {
orm: MikroORM | null
manager: SqlEntityManager | null
setupDatabase(): Promise<void>
clearDatabase(): Promise<void>
getManager(): SqlEntityManager
forkManager(): Promise<SqlEntityManager>
getORM(): MikroORM
}
export const TestDatabase: TestDatabase = {
orm: null,
manager: null,
getManager() {
if (this.manager === null) {
throw new Error("manager entity not available")
}
return this.manager
},
async forkManager() {
if (this.manager === null) {
throw new Error("manager entity not available")
}
return await this.manager.fork()
},
getORM() {
if (this.orm === null) {
throw new Error("orm entity not available")
}
return this.orm
},
async setupDatabase() {
// Initializing the ORM
this.orm = await MikroORM.init(ORMConfig)
if (this.orm === null) {
throw new Error("ORM not configured")
}
this.manager = await this.orm.em
await this.orm.schema.refreshDatabase() // ensure db exists and is fresh
},
async clearDatabase() {
if (this.orm === null) {
throw new Error("ORM not configured")
}
await this.orm.close()
this.orm = null
this.manager = null
},
}
@@ -1,40 +0,0 @@
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
import { DB_URL } from "./database"
import { EventBusService } from "../__fixtures__/event-bus"
export function getInitModuleConfig(
additionalOptions: any = {},
injectedDependencies: null | Record<string, any> = null
) {
const moduleOptions = {
defaultAdapterOptions: {
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_PRODUCT_DB_SCHEMA,
},
},
...additionalOptions,
}
const modulesConfig_ = {
[Modules.PRODUCT]: {
definition: ModulesDefinition[Modules.PRODUCT],
options: moduleOptions,
},
}
const defaultInjectedDependencies = {
eventBusModuleService: new EventBusService(),
}
return {
injectedDependencies: injectedDependencies ?? defaultInjectedDependencies,
modulesConfig: modulesConfig_,
databaseConfig: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_PRODUCT_DB_SCHEMA,
},
joinerConfig: [],
}
}
@@ -1,2 +0,0 @@
export * from "./database"
export * from "./get-init-module-config"
-2
View File
@@ -17,6 +17,4 @@ module.exports = {
testEnvironment: `node`,
moduleFileExtensions: [`js`, `ts`],
modulePathIgnorePatterns: ["dist/"],
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
}
@@ -693,7 +693,6 @@ export default class ProductModuleService<
@MedusaContext() sharedContext: Context = {}
): Promise<ProductTypes.ProductDTO[] | ProductTypes.ProductDTO> {
const input = Array.isArray(data) ? data : [data]
const products = await this.create_(input, sharedContext)
const createdProducts = await this.baseRepository_.serialize<
@@ -1,45 +1,21 @@
import { Modules } from "@medusajs/modules-sdk"
import { IPromotionModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { initModules } from "medusa-test-utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { createCampaigns } from "../../../__fixtures__/campaigns"
import { createPromotions } from "../../../__fixtures__/promotion"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
jest.setTimeout(30000)
describe("Promotion Module Service: Campaigns", () => {
let service: IPromotionModuleService
let repositoryManager: SqlEntityManager
let shutdownFunc: () => void
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PROMOTION]
shutdownFunc = shutdown
})
afterAll(async () => {
shutdownFunc()
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = MikroOrmWrapper.forkManager()
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
moduleIntegrationTestRunner({
moduleName: Modules.PROMOTION,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPromotionModuleService>) => {
describe("Promotion Module Service: Campaigns", () => {
describe("listAndCountCampaigns", () => {
beforeEach(async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
})
it("should return all campaigns and its count", async () => {
@@ -179,7 +155,7 @@ describe("Promotion Module Service: Campaigns", () => {
})
it("should create a basic campaign with promotions successfully", async () => {
await createPromotions(repositoryManager)
await createPromotions(MikroOrmWrapper.forkManager())
const startsAt = new Date("01/01/2024")
const endsAt = new Date("01/01/2025")
@@ -230,7 +206,7 @@ describe("Promotion Module Service: Campaigns", () => {
})
it("should update the attributes of a campaign successfully", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [updatedCampaign] = await service.updateCampaigns([
{
@@ -255,7 +231,7 @@ describe("Promotion Module Service: Campaigns", () => {
})
it("should update the attributes of a campaign budget successfully", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [updatedCampaign] = await service.updateCampaigns([
{
@@ -278,8 +254,8 @@ describe("Promotion Module Service: Campaigns", () => {
})
it("should update promotions of a campaign successfully", async () => {
await createCampaigns(repositoryManager)
await createPromotions(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
await createPromotions(MikroOrmWrapper.forkManager())
const [updatedCampaign] = await service.updateCampaigns([
{
@@ -313,8 +289,8 @@ describe("Promotion Module Service: Campaigns", () => {
})
it("should remove promotions of the campaign successfully", async () => {
await createCampaigns(repositoryManager)
await createPromotions(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
await createPromotions(MikroOrmWrapper.forkManager())
await service.updateCampaigns({
id: "campaign-id-1",
@@ -340,7 +316,7 @@ describe("Promotion Module Service: Campaigns", () => {
describe("retrieveCampaign", () => {
beforeEach(async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
})
const id = "campaign-id-1"
@@ -452,7 +428,9 @@ describe("Promotion Module Service: Campaigns", () => {
await service.softDeleteCampaigns([createdCampaign.id])
let campaigns = await service.listCampaigns({ id: [createdCampaign.id] })
let campaigns = await service.listCampaigns({
id: [createdCampaign.id],
})
expect(campaigns).toHaveLength(0)
await service.restoreCampaigns([createdCampaign.id])
@@ -461,4 +439,6 @@ describe("Promotion Module Service: Campaigns", () => {
expect(campaigns).toHaveLength(1)
})
})
})
},
})
@@ -1,42 +1,18 @@
import { Modules } from "@medusajs/modules-sdk"
import { IPromotionModuleService } from "@medusajs/types"
import { ApplicationMethodType, PromotionType } from "@medusajs/utils"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { initModules } from "medusa-test-utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { createCampaigns } from "../../../__fixtures__/campaigns"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
jest.setTimeout(30000)
describe("Promotion Service: computeActions", () => {
let service: IPromotionModuleService
let repositoryManager: SqlEntityManager
let shutdownFunc: () => void
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PROMOTION]
shutdownFunc = shutdown
})
afterAll(async () => {
shutdownFunc()
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = MikroOrmWrapper.forkManager()
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
moduleIntegrationTestRunner({
moduleName: Modules.PROMOTION,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPromotionModuleService>) => {
describe("Promotion Service: computeActions", () => {
describe("when code is not present in database", () => {
it("should return empty array when promotion does not exist", async () => {
const response = await service.computeActions(["DOES_NOT_EXIST"], {
@@ -469,7 +445,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type spend", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -532,7 +508,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type usage", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -902,7 +878,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type spend", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -960,7 +936,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type usage", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -1404,7 +1380,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type spend", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -1461,7 +1437,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type usage", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -1914,7 +1890,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type spend", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -1971,7 +1947,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type usage", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -2478,7 +2454,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type spend", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -2532,7 +2508,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type usage", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -3052,7 +3028,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type spend", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -3106,7 +3082,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type usage", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -3542,7 +3518,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type spend", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -3595,7 +3571,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type usage", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -4028,7 +4004,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type spend", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -4081,7 +4057,7 @@ describe("Promotion Service: computeActions", () => {
})
it("should compute budget exceeded action when applicable total exceeds campaign budget for type usage", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await service.create([
{
@@ -4748,7 +4724,10 @@ describe("Promotion Service: computeActions", () => {
},
])
const result = await service.computeActions(["PROMOTION_TEST"], context)
const result = await service.computeActions(
["PROMOTION_TEST"],
context
)
expect(result).toEqual([
{
@@ -4840,7 +4819,10 @@ describe("Promotion Service: computeActions", () => {
},
])
const result = await service.computeActions(["PROMOTION_TEST"], context)
const result = await service.computeActions(
["PROMOTION_TEST"],
context
)
expect(result).toEqual([])
})
@@ -4925,7 +4907,10 @@ describe("Promotion Service: computeActions", () => {
},
])
const result = await service.computeActions(["PROMOTION_TEST"], context)
const result = await service.computeActions(
["PROMOTION_TEST"],
context
)
expect(result).toEqual([
{
@@ -5023,9 +5008,14 @@ describe("Promotion Service: computeActions", () => {
},
])
const result = await service.computeActions(["PROMOTION_TEST"], context)
const result = await service.computeActions(
["PROMOTION_TEST"],
context
)
expect(result).toEqual([])
})
})
})
},
})
@@ -6,43 +6,19 @@ import {
CampaignBudgetType,
PromotionType,
} from "@medusajs/utils"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { initModules } from "medusa-test-utils"
import { createCampaigns } from "../../../__fixtures__/campaigns"
import { createPromotions } from "../../../__fixtures__/promotion"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
describe("Promotion Service", () => {
let service: IPromotionModuleService
let repositoryManager: SqlEntityManager
let shutdownFunc: () => void
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PROMOTION]
shutdownFunc = shutdown
})
afterAll(async () => {
shutdownFunc()
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = MikroOrmWrapper.forkManager()
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
moduleIntegrationTestRunner({
moduleName: Modules.PROMOTION,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPromotionModuleService>) => {
describe("Promotion Service", () => {
describe("create", () => {
it("should throw an error when required params are not passed", async () => {
const error = await service
@@ -165,7 +141,7 @@ describe("Promotion Service", () => {
const startsAt = new Date("01/01/2023")
const endsAt = new Date("01/01/2023")
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const createdPromotion = await service.create({
code: "PROMOTION_TEST",
@@ -209,7 +185,7 @@ describe("Promotion Service", () => {
})
it("should create a basic promotion with an existing campaign successfully", async () => {
await createCampaigns(repositoryManager)
await createCampaigns(MikroOrmWrapper.forkManager())
const createdPromotion = await service.create({
code: "PROMOTION_TEST",
@@ -415,7 +391,9 @@ describe("Promotion Service", () => {
])
.catch((e) => e)
expect(error.message).toContain("rules[].attribute is a required field")
expect(error.message).toContain(
"rules[].attribute is a required field"
)
})
it("should throw an error when rule operator is invalid", async () => {
@@ -435,7 +413,9 @@ describe("Promotion Service", () => {
])
.catch((e) => e)
expect(error.message).toContain("rules[].operator is a required field")
expect(error.message).toContain(
"rules[].operator is a required field"
)
error = await service
.create([
@@ -666,7 +646,7 @@ describe("Promotion Service", () => {
})
it("should update the attributes of a promotion successfully", async () => {
await createPromotions(repositoryManager)
await createPromotions(MikroOrmWrapper.forkManager())
const [updatedPromotion] = await service.update([
{
@@ -823,15 +803,18 @@ describe("Promotion Service", () => {
})
it("should update campaign of the promotion", async () => {
await createCampaigns(repositoryManager)
const [createdPromotion] = await createPromotions(repositoryManager, [
await createCampaigns(MikroOrmWrapper.forkManager())
const [createdPromotion] = await createPromotions(
MikroOrmWrapper.forkManager(),
[
{
is_automatic: true,
code: "TEST",
type: PromotionType.BUYGET,
campaign_id: "campaign-id-1",
},
])
]
)
const [updatedPromotion] = await service.update([
{
@@ -852,7 +835,7 @@ describe("Promotion Service", () => {
describe("retrieve", () => {
beforeEach(async () => {
await createPromotions(repositoryManager)
await createPromotions(MikroOrmWrapper.forkManager())
})
const id = "promotion-id-1"
@@ -908,7 +891,7 @@ describe("Promotion Service", () => {
describe("listAndCount", () => {
beforeEach(async () => {
await createPromotions(repositoryManager, [
await createPromotions(MikroOrmWrapper.forkManager(), [
{
id: "promotion-id-1",
code: "PROMOTION_1",
@@ -1234,7 +1217,10 @@ describe("Promotion Service", () => {
let error
try {
await service.addPromotionBuyRules(undefined as unknown as string, [])
await service.addPromotionBuyRules(
undefined as unknown as string,
[]
)
} catch (e) {
error = e
}
@@ -1243,13 +1229,16 @@ describe("Promotion Service", () => {
})
it("should successfully create buy rules for a buyget promotion", async () => {
const promotionRules = await service.addPromotionBuyRules(promotion.id, [
const promotionRules = await service.addPromotionBuyRules(
promotion.id,
[
{
attribute: "product.id",
operator: "in",
values: ["prod_3", "prod_4"],
},
])
]
)
expect(promotionRules).toEqual([
expect.objectContaining({
@@ -1309,7 +1298,10 @@ describe("Promotion Service", () => {
let error
try {
await service.removePromotionRules(undefined as unknown as string, [])
await service.removePromotionRules(
undefined as unknown as string,
[]
)
} catch (e) {
error = e
}
@@ -1497,4 +1489,6 @@ describe("Promotion Service", () => {
)
})
})
})
},
})
@@ -1,41 +1,19 @@
import { Modules } from "@medusajs/modules-sdk"
import { IPromotionModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { initModules } from "medusa-test-utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { createCampaigns } from "../../../__fixtures__/campaigns"
import { MikroOrmWrapper } from "../../../utils"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
jest.setTimeout(30000)
describe("Promotion Service: campaign usage", () => {
let service: IPromotionModuleService
let repositoryManager: SqlEntityManager
let shutdownFunc: () => void
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.PROMOTION]
shutdownFunc = shutdown
})
afterAll(async () => {
shutdownFunc()
})
moduleIntegrationTestRunner({
moduleName: Modules.PROMOTION,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPromotionModuleService>) => {
describe("Promotion Service: campaign usage", () => {
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = MikroOrmWrapper.forkManager()
await createCampaigns(repositoryManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
await createCampaigns(MikroOrmWrapper.forkManager())
})
describe("registerUsage", () => {
@@ -206,4 +184,6 @@ describe("Promotion Service: campaign usage", () => {
)
})
})
})
},
})
@@ -1,35 +1,20 @@
import { createMedusaContainer, PromotionType } from "@medusajs/utils"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { PromotionService } from "@services"
import { PromotionType } from "@medusajs/utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { createPromotions } from "../../../__fixtures__/promotion"
import { MikroOrmWrapper } from "../../../utils"
import { asValue } from "awilix"
import ContainerLoader from "../../../../src/loaders/container"
import { IPromotionModuleService } from "@medusajs/types"
import { Modules } from "@medusajs/modules-sdk"
jest.setTimeout(30000)
describe("Promotion Service", () => {
let service: PromotionService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
moduleIntegrationTestRunner({
moduleName: Modules.PROMOTION,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IPromotionModuleService>) => {
describe("Promotion Service", () => {
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
testManager = await MikroOrmWrapper.forkManager()
const container = createMedusaContainer()
container.register("manager", asValue(repositoryManager))
await ContainerLoader({ container })
service = container.resolve("promotionService")
await createPromotions(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
await createPromotions(MikroOrmWrapper.forkManager())
})
describe("create", () => {
@@ -68,4 +53,6 @@ describe("Promotion Service", () => {
)
})
})
})
},
})
@@ -1,6 +0,0 @@
if (typeof process.env.DB_TEMP_NAME === "undefined") {
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
process.env.DB_TEMP_NAME = `medusa-promotion-integration-${tempName}`
}
process.env.MEDUSA_PROMOTION_DB_SCHEMA = "public"
@@ -1,3 +0,0 @@
import { JestUtils } from "medusa-test-utils"
JestUtils.afterAllHookDropDatabase()
@@ -1,6 +0,0 @@
import { ModuleServiceInitializeOptions } from "@medusajs/types"
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
schema: "public",
clientUrl: "medusa-promotion-test",
}
@@ -1,18 +0,0 @@
import {TestDatabaseUtils} from "medusa-test-utils"
import * as PromotionModels from "@models"
const pathToMigrations = "../../src/migrations"
const mikroOrmEntities = PromotionModels as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper({
mikroOrmEntities,
pathToMigrations,
})
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig({
mikroOrmEntities,
pathToMigrations,
})
export const DB_URL = TestDatabaseUtils.getDatabaseURL()
@@ -1,33 +0,0 @@
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
import { DB_URL } from "./database"
export function getInitModuleConfig() {
const moduleOptions = {
defaultAdapterOptions: {
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_PROMOTION_DB_SCHEMA,
},
},
}
const injectedDependencies = {}
const modulesConfig_ = {
[Modules.PROMOTION]: {
definition: ModulesDefinition[Modules.PROMOTION],
options: moduleOptions,
},
}
return {
injectedDependencies,
modulesConfig: modulesConfig_,
databaseConfig: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_PROMOTION_DB_SCHEMA,
},
joinerConfig: [],
}
}
@@ -1,2 +0,0 @@
export * from "./config"
export * from "./database"
-2
View File
@@ -18,6 +18,4 @@ module.exports = {
testEnvironment: `node`,
moduleFileExtensions: [`js`, `ts`],
modulePathIgnorePatterns: ["dist/"],
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
}
@@ -1,30 +1,16 @@
import { Modules } from "@medusajs/modules-sdk"
import { IRegionModuleService } from "@medusajs/types"
import { initModules } from "medusa-test-utils"
import { MikroOrmWrapper } from "../utils"
import { getInitModuleConfig } from "../utils/get-init-module-config"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
describe("Region Module Service", () => {
let service: IRegionModuleService
let shutdownFunc: () => Promise<void>
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.REGION]
shutdownFunc = shutdown
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
await shutdownFunc()
})
moduleIntegrationTestRunner({
moduleName: Modules.REGION,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IRegionModuleService>) => {
describe("Region Module Service", () => {
it("should create countries on application start", async () => {
const countries = await service.listCountries({}, { take: null })
expect(countries.length).toEqual(250)
@@ -251,7 +237,10 @@ describe("Region Module Service", () => {
currency_code: "mxn",
})
expect(updatedRegion.countries.map((c) => c.iso_2)).toEqual(["ca", "us"])
expect(updatedRegion.countries.map((c) => c.iso_2)).toEqual([
"ca",
"us",
])
})
it("should remove the countries in a region successfully", async () => {
@@ -359,4 +348,6 @@ describe("Region Module Service", () => {
expect(resp.countries).toHaveLength(2)
})
})
},
})
@@ -1,8 +0,0 @@
if (typeof process.env.DB_TEMP_NAME === "undefined") {
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
process.env.DB_TEMP_NAME = `medusa-region-integration-${tempName}`
}
process.env.MEDUSA_REGION_DB_SCHEMA = "public"
// TODO: Remove this when all modules are migrated to v2
process.env.MEDUSA_FF_MEDUSA_V2 = true
@@ -1,3 +0,0 @@
import { JestUtils } from "medusa-test-utils"
JestUtils.afterAllHookDropDatabase()
@@ -1,6 +0,0 @@
import { ModuleServiceInitializeOptions } from "@medusajs/types"
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
schema: "public",
clientUrl: "medusa-region-test",
}
@@ -1,18 +0,0 @@
import {TestDatabaseUtils} from "medusa-test-utils"
import * as RegionModels from "@models"
const pathToMigrations = "../../src/migrations"
const mikroOrmEntities = RegionModels as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper({
mikroOrmEntities,
pathToMigrations,
})
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig({
mikroOrmEntities,
pathToMigrations,
})
export const DB_URL = TestDatabaseUtils.getDatabaseURL()
@@ -1,33 +0,0 @@
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
import { DB_URL } from "./database"
export function getInitModuleConfig() {
const moduleOptions = {
defaultAdapterOptions: {
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_REGION_DB_SCHEMA,
},
},
}
const injectedDependencies = {}
const modulesConfig_ = {
[Modules.REGION]: {
definition: ModulesDefinition[Modules.REGION],
options: moduleOptions,
},
}
return {
injectedDependencies,
modulesConfig: modulesConfig_,
databaseConfig: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_REGION_DB_SCHEMA,
},
joinerConfig: [],
}
}
@@ -1,3 +0,0 @@
export * from "./config"
export * from "./database"
-2
View File
@@ -17,6 +17,4 @@ module.exports = {
testEnvironment: `node`,
moduleFileExtensions: [`js`, `ts`],
modulePathIgnorePatterns: ["dist/"],
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
}
@@ -1,12 +1,9 @@
import { IUserModuleService } from "@medusajs/types/dist/user"
import { MikroOrmWrapper } from "../../../utils"
import { MockEventBusService } from "medusa-test-utils"
import { Modules } from "@medusajs/modules-sdk"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { UserEvents } from "@medusajs/utils"
import { createInvites } from "../../../__fixtures__/invite"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { initModules } from "medusa-test-utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
@@ -28,38 +25,26 @@ const defaultInviteData = [
},
]
describe("UserModuleService - Invite", () => {
let service: IUserModuleService
let testManager: SqlEntityManager
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.USER]
shutdownFunc = shutdown
})
moduleIntegrationTestRunner({
moduleName: Modules.USER,
moduleOptions: {
jwt_secret: "test",
},
injectedDependencies: {
eventBusModuleService: new MockEventBusService(),
},
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IUserModuleService>) => {
describe("UserModuleService - Invite", () => {
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
testManager = MikroOrmWrapper.forkManager()
jest.clearAllMocks()
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
afterAll(async () => {
await shutdownFunc()
})
describe("listInvites", () => {
it("should list invites", async () => {
await createInvites(testManager, defaultInviteData)
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
const invites = await service.listInvites()
@@ -74,7 +59,7 @@ describe("UserModuleService - Invite", () => {
})
it("should list invites by id", async () => {
await createInvites(testManager, defaultInviteData)
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
const invites = await service.listInvites({
id: ["1"],
})
@@ -89,7 +74,7 @@ describe("UserModuleService - Invite", () => {
describe("listAndCountInvites", () => {
it("should list and count invites", async () => {
await createInvites(testManager, defaultInviteData)
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
const [invites, count] = await service.listAndCountInvites()
expect(count).toEqual(2)
@@ -104,7 +89,7 @@ describe("UserModuleService - Invite", () => {
})
it("should listAndCount invites by id", async () => {
await createInvites(testManager, defaultInviteData)
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
const [invites, count] = await service.listAndCountInvites({
id: "1",
})
@@ -122,7 +107,7 @@ describe("UserModuleService - Invite", () => {
const id = "1"
it("should return an invite for the given id", async () => {
await createInvites(testManager, defaultInviteData)
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
const invite = await service.retrieveInvite(id)
expect(invite).toEqual(
@@ -151,7 +136,7 @@ describe("UserModuleService - Invite", () => {
})
it("should return invite based on config select param", async () => {
await createInvites(testManager, defaultInviteData)
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
const invite = await service.retrieveInvite(id, {
select: ["id"],
})
@@ -172,11 +157,13 @@ describe("UserModuleService - Invite", () => {
])
.catch((e) => e)
expect(error.message).toEqual('Invite with id "does-not-exist" not found')
expect(error.message).toEqual(
'Invite with id "does-not-exist" not found'
)
})
it("should emit invite updated events", async () => {
await createInvites(testManager, defaultInviteData)
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
jest.clearAllMocks()
@@ -202,7 +189,7 @@ describe("UserModuleService - Invite", () => {
describe("resendInvite", () => {
it("should emit token generated event for invites", async () => {
await createInvites(testManager, defaultInviteData)
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
await service.refreshInviteTokens(["1"])
@@ -267,4 +254,6 @@ describe("UserModuleService - Invite", () => {
])
})
})
})
},
})
@@ -1,12 +1,9 @@
import { IUserModuleService } from "@medusajs/types/dist/user"
import { MikroOrmWrapper } from "../../../utils"
import { MockEventBusService } from "medusa-test-utils"
import { Modules } from "@medusajs/modules-sdk"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { UserEvents } from "@medusajs/utils"
import { createUsers } from "../../../__fixtures__/user"
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
import { initModules } from "medusa-test-utils"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(30000)
@@ -21,38 +18,27 @@ const defaultUserData = [
},
]
describe("UserModuleService - User", () => {
let service: IUserModuleService
let testManager: SqlEntityManager
let shutdownFunc: () => Promise<void>
beforeAll(async () => {
const initModulesConfig = getInitModuleConfig()
const { medusaApp, shutdown } = await initModules(initModulesConfig)
service = medusaApp.modules[Modules.USER]
shutdownFunc = shutdown
})
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
testManager = MikroOrmWrapper.forkManager()
})
moduleIntegrationTestRunner({
moduleName: Modules.USER,
moduleOptions: {
jwt_secret: "test",
},
injectedDependencies: {
eventBusModuleService: new MockEventBusService(),
},
testSuite: ({
MikroOrmWrapper,
service,
medusaApp,
}: SuiteOptions<IUserModuleService>) => {
describe("UserModuleService - User", () => {
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
jest.clearAllMocks()
})
afterAll(async () => {
await shutdownFunc()
})
describe("list", () => {
it("should list users", async () => {
await createUsers(testManager, defaultUserData)
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
const users = await service.list()
@@ -67,7 +53,7 @@ describe("UserModuleService - User", () => {
})
it("should list users by id", async () => {
await createUsers(testManager, defaultUserData)
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
const users = await service.list({
id: ["1"],
})
@@ -82,7 +68,7 @@ describe("UserModuleService - User", () => {
describe("listAndCount", () => {
it("should list and count users", async () => {
await createUsers(testManager, defaultUserData)
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
const [users, count] = await service.listAndCount()
expect(count).toEqual(2)
@@ -97,7 +83,7 @@ describe("UserModuleService - User", () => {
})
it("should list and count users by id", async () => {
await createUsers(testManager, defaultUserData)
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
const [Users, count] = await service.listAndCount({
id: "1",
})
@@ -115,7 +101,7 @@ describe("UserModuleService - User", () => {
const id = "1"
it("should return an user for the given id", async () => {
await createUsers(testManager, defaultUserData)
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
const user = await service.retrieve(id)
@@ -143,7 +129,7 @@ describe("UserModuleService - User", () => {
})
it("should return user based on config select param", async () => {
await createUsers(testManager, defaultUserData)
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
const User = await service.retrieve(id, {
select: ["id"],
@@ -161,7 +147,7 @@ describe("UserModuleService - User", () => {
const id = "1"
it("should delete the users given an id successfully", async () => {
await createUsers(testManager, defaultUserData)
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
await service.delete([id])
@@ -183,7 +169,9 @@ describe("UserModuleService - User", () => {
])
.catch((e) => e)
expect(error.message).toEqual('User with id "does-not-exist" not found')
expect(error.message).toEqual(
'User with id "does-not-exist" not found'
)
})
it("should emit user created events", async () => {
@@ -248,4 +236,6 @@ describe("UserModuleService - User", () => {
])
})
})
})
},
})
@@ -1,6 +0,0 @@
if (typeof process.env.DB_TEMP_NAME === "undefined") {
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
process.env.DB_TEMP_NAME = `medusa-user-integration-${tempName}`
}
process.env.MEDUSA_USER_DB_SCHEMA = "public"
-3
View File
@@ -1,3 +0,0 @@
import { JestUtils } from "medusa-test-utils"
JestUtils.afterAllHookDropDatabase()
@@ -1,6 +0,0 @@
import { ModuleServiceInitializeOptions } from "@medusajs/types"
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
schema: "public",
clientUrl: "medusa-user-test",
}
@@ -1,18 +0,0 @@
import * as UserModels from "@models"
import {TestDatabaseUtils} from "medusa-test-utils"
const pathToMigrations = "../../src/migrations"
const mikroOrmEntities = UserModels as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper({
mikroOrmEntities,
pathToMigrations,
})
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig({
mikroOrmEntities,
pathToMigrations,
})
export const DB_URL = TestDatabaseUtils.getDatabaseURL()
@@ -1,37 +0,0 @@
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
import { DB_URL } from "./database"
import { MockEventBusService } from "medusa-test-utils"
export function getInitModuleConfig() {
const moduleOptions = {
defaultAdapterOptions: {
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_USER_DB_SCHEMA,
},
},
jwt_secret: "test",
}
const injectedDependencies = {
eventBusModuleService: new MockEventBusService(),
}
const modulesConfig_ = {
[Modules.USER]: {
definition: ModulesDefinition[Modules.USER],
options: moduleOptions,
},
}
return {
injectedDependencies,
modulesConfig: modulesConfig_,
databaseConfig: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_USER_DB_SCHEMA,
},
joinerConfig: [],
}
}
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more