Giter Club home page Giter Club logo

commercetools-node-mock's Introduction

Commercetools Mocking library for Node

codecov

This library mocks the Commercetools rest API to ease testing of your typescript codebases interacting with the commercetools api. It uses the same proven approach as our testing module in the commercetools Python SDK.

Since version 2 of this library it is based on msw instead of nock. It is now therefore als recommended to manage the msw server yourself and use the registerHandlers method to register the handlers on this server.

This allows you to use the same server for mocking other API's as well.

Installation

yarn add --dev @labdigital/commercetools-mock

Docker image

This codebase is also available as a docker image where it provides a runnable http server exposing the mocked endpoints. See https://hub.docker.com/r/labdigital/commercetools-mock-server

Example

import { CommercetoolsMock, getBaseResourceProperties } from '@labdigital/commercetools-mock'
import { setupServer } from 'msw/node'

const ctMock = new CommercetoolsMock({
  apiHost: 'https://localhost',
  authHost: 'https://localhost',
  enableAuthentication: false,
  validateCredentials: false,
  defaultProjectKey: 'my-project',
  silent: true,
})

describe('A module', () => {
  const mswServer = setupServer()

  beforeAll(() => {
    mswServer.listen({ onUnhandledRequest: "error" })
  })

  beforeEach(() => {
    ctMock.registerHandlers(mswServer)

    ctMock.project().add('type', {
      ...getBaseResourceProperties()
      key: 'my-customt-type',
      fieldDefinitions: [],
    })
  })

  afterAll(() => {
    mswServer.close()
  })

  afterEach(() => {
    server.clearHandlers()
    ctMock.clear()
  })

  test('my function', async () => {
    ctMock.project().add('customer', customerFixture)

    const res = await myFunction()

    expect(res).toEqual(true)
  })
})

Contributing

This codebases use @changesets for release and version management

  • Create a feature branch with new features / fixes (see Adding a new service)
  • When your code changes are complete, add a changeset file to your feature branch using pnpm changeset
  • Create a PR to request your changes to be merged to main
  • After your PR is merged, GitHub actions will create a release PR or add your changeset to an existing release PR
  • When the release is ready merge the release branch. A new version will be released

Adding a new service {#adding-a-service}

Implement the following:

  • New repository in src/repositories
  • New service in src/services
  • Add new service to src/ctMock.ts ctMock._services
  • Add new service to src/storage.ts InMemoryStorage
  • Adjust src/types.ts RepositoryMap and possibly serviceTypes

commercetools-node-mock's People

Contributors

bala-goflink avatar blurrah avatar bramkaashoek avatar bulat-khusnimardanov avatar davidweterings avatar demeyerthom avatar fabiodiceglie avatar github-actions[bot] avatar leongraumans avatar mikedebock avatar mvantellingen avatar okkevandereijk avatar onur9 avatar stephanbeek avatar teddyteh avatar tiagoumemura avatar tleguijt avatar vaimo-wilko avatar victoravelar avatar whyhankee avatar willstaff avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

commercetools-node-mock's Issues

size-limit PR check not working

Unclear how to fix it, it seems related to ai/size-limit#105

Tried renaming package.json size-limit module names to '-' but it leads to external package errors like:

ERROR in ./node_modules/express/lib/request.js
Module not found: Error: Can't resolve 'net' in '/Users/david/dev/labdigital/katogroup/commercetools-node-mock/node_modules/express/lib'

devDependencies and peerDependencies for @commercetools/platform-sdk

Hi,

I am a very happy user of this library, thank you for it!

Right now I have to update @commercetools/platform-sdk (2.X --> 4.X) and @commercetools/sdk-client-v2 (1.C --> 2.X) in my project, but I am having conflicts regarding this library.

In fact, in the v1.2 package.json of this library the @commercetools/platform-sdk package is listed in both devDependencies and peerDependencies, but with different versions:

  "devDependencies": {
    ...
    "@commercetools/platform-sdk": "4.0.0",
    ...
  },
  "peerDependencies": {
    "@commercetools/platform-sdk": "^2.4.1"
  }

As per my understanding, devDependencies should contain packages that are required during development, while peerDependencies should declare compatibility requirements with other packages. Having the same package with different versions in these sections seems unusual and might lead to conflicts during the dependency resolution process.

I wanted to reach out to you and inquire if there is a specific reason for this version discrepancy. Is it intentional, or is there a compatibility consideration that I might be missing?

Thanks,
Lorenzo

Creating standalone price returns (Typedmoney) value as nil

Trying to create price as

price := platform.StandalonePriceDraft{
                          Sku: "1111111",
                          Value: platform.Money{
				CentAmount:   2000,
				CurrencyCode: "EUR",
			},
			Country: &country,
			Active:        &active,
}

result, err = c.client.StandalonePrices().Post(price).Execute(ctx)

After creating price returned with price.Value as nil

??

Provide more examples or test cases

Hey,

The library looks interesting and might help us to reduce lots of boilerplate test code.

I tried the example in the readme but unfortunately, it did not work for me, could you provide more examples of how it could be used, I could not see any tests in a project to inspire.

Regards, Ahmet.

Oauth token invalid grant_type

Weird issue using this package (v0.2.1). When I debug and intercept the tokenHandler, it passes the x-www-form-urlencoded body everywhere, but in the mocker itself there is no body:

application code -> commercetools sdk -> ctMock.mockAuthHost has the body for the token.

OAuth2Server.tokenHandler has empty request.body and empty request.query

Already tried adding:

projectRouter.use(express.urlencoded({ extended: true }))

locally with yarn link, but same issue.

Unpublished products

Hi,

It seems as if currently the library doesn't support mocking of unpublished products, when fetching via a product projection search.

transform(product: Product): ProductProjection {
const obj = product.masterData.current
return {
id: product.id,
createdAt: product.createdAt,
lastModifiedAt: product.lastModifiedAt,
version: product.version,
name: obj.name,
key: product.key,
description: obj.description,
metaDescription: obj.metaDescription,
slug: obj.slug,
categories: obj.categories,
masterVariant: obj.masterVariant,
variants: obj.variants,
productType: product.productType,
}
}

Please could this be added?

Best regards

Is standalone price supported? Error Request returned status code 404

Hi,

I am trying to write mock tests for creating and reading standalone prices in the commerce tool.

Created client as->
ENV:
CTP_PROJECT_KEY=unittest
CTP_API_URL=http://localhost:8989
CTP_AUTH_URL=http://localhost:8989/oauth/token
PRICING_CT_CLIENT_ID=unittest
PRICING_CT_CLIENT_SECRET=unittest
CTP_SCOPES=manage_project:todo

Error:
Trying to get or set standalone price but getting error as Request returned status code 404
POST /oauth/token 200 100 - 63.845 ms
GET /unittest/standalone-prices?expand=channel&limit=500&offset=0&sort=lastModifiedAt+asc 404 165 - 23.144 ms
POST /oauth/token 200 100 - 13.803 ms
POST /unittest/standalone-prices 404 166 - 49.026 ms

Should I include anything here?

Implement product-projection suggest endpoint

Hello,

I was looking to test the suggest endpoint using your awesome project but it doesn't seem supported !
Are you guys planning to add this feature to the project any time soon ?
If not would you have some pointers if I found the time and courage to start implementing this ?

Thanks for your hard work!

Product projection is not a separate resource

The product projection mocking is not implemented correctly. It should be an interface which searches the product resources instead.

So the same as for example the my-* services

Auth mock

would be nice to have post(/oauth/token) with a mock response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.