Skip to content

Provides a way for testing Appsync functions locally using CDK.

Notifications You must be signed in to change notification settings

icsaba/appsync-mock

Repository files navigation

Appsync Mock

It's a library for testing Appsync locally using CDK and AppsyncHelper. The mock tries to create the Appsync environment, so we can run and test functions, resolvers and pipeline resolvers locally on our machine with mocked datasources.

Usage

I am using vitest but jest should be very similar.

vitest.config.ts

import { defineConfig } from 'vitest/config'

export default defineConfig({
  resolve: { 
    alias: { 
      // https://github.com/vitest-dev/vitest/issues/4605
      graphql: "graphql/index.js",

      // replace import.meta.dirname with the cloned repo path
      "@aws-appsync/utils": `${import.meta.dirname}/@aws-appsync-utils`
    } 
  },
});

*.spec.ts

For further references, you can check the tests files in the repo.

let appsync;

beforeAll(async () => {
  const stack = createStack(); // should return yout cdk stack
  appsync = new AppSyncMock(stack, 'MyBackendApi', true);
});

describe('Simple cases', () => {
  it('should return with data from datasource', async () => {
    const resolver = appsync.getResolver('Query.users');
    resolver
      .addDefaultContext({ arguments: { input: { id: 'valid' } } } as Context)
      .addMockDataSource('users', usersDynamoTable);

    const resultContext = await resolver.run();

    expect(resultContext.result).toEqual(
      [{ id: 1, name: 'test', email: '[email protected]', address: '1234 Main St'}]
    );
  });  
});

Mock datasource is a function:

const usersDynamoTable = vi.fn().mockImplementation(({ id }: { id: number }) => {
  const items = [
    { id: 1, name: 'test bar', email: '[email protected]', address: '1234 Main St' },
    { id: 2, name: 'test foo', email: '[email protected]', address: '1235 Sub St' }
  ];

  if (!!id && typeof id === 'number') {
    return { items: [items.find( item => item.id === id )] };
  }

  return { items };
});

Contributing

Feel free to create a PR and extend the @aws-appsync/utils mock any time or just create an issue.

About

Provides a way for testing Appsync functions locally using CDK.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published