본문 바로가기
WIKI 기술 지식 베이스

커스텀 액션 단위 테스트

원문 보기 위키 갱신

단위 테스트는 커스텀 액션 기능의 회귀(regression)를 방지하는 데 도움이 됩니다. 커스텀 액션의 핵심인 createTemplateAction 함수는 목(mock) 처리하기 어려울 수 있습니다. 도움이 되는 헬퍼 메서드가 있습니다.

출처: 문서

본문

단위 테스트는 커스텀 액션 기능의 회귀를 방지하는 데 도움이 됩니다. 커스텀 액션의 핵심인 createTemplateAction 함수는 목 처리하기 어려울 수 있습니다. 도움이 되는 헬퍼 메서드가 있습니다.

컨텍스트 목 처리

createTemplateAction 입력 객체의 handler 속성은 컨텍스트를 기대합니다. 아래 코드를 사용해 목 컨텍스트를 만들 수 있습니다.

import { createMockActionContext } from '@backstage/plugin-scaffolder-node-test-utils';const mockContext = createMockActionContext({  input: { repoUrl: 'dev.azure.com?repo=repo&owner=owner&organization=org' },});await action.handler(mockContext);expect(mockContext.output).toHaveBeenCalledWith(  'remoteUrl',  'https://dev.azure.com/organization/project/_git/repo',);

컨텍스트 객체 안에서 워크스페이스 목 처리

주의할 점이 하나 있습니다. it 안에서 createMockActionContext를 호출하고 싶다면 workspacePath를 제공해야 합니다. 기본적으로 createMockActionContext는 import { createMockDirectory } from '@backstage/backend-test-utils';를 사용해 그것을 만들어 줍니다. 아래 코드를 사용해 createMockActionContext 함수의 기본 워크스페이스를 사용하지 않고 workspacePath를 커스터마이즈할 수 있습니다.

describe('github:autolinks:create', async () => {  const workspacePath = createMockDirectory().resolve('workspace');  // ...  it('should call the githubApis for creating alphanumeric autolink reference', async () => {    // ...    await action.handler(      createMockActionContext({        input: {          repoUrl: 'github.com?repo=repo&owner=owner',          keyPrefix: 'TICKET-',          urlTemplate: 'https://example.com/TICKET?query=<num>',        },        workspacePath,      }),    );    //...  });});

Config 핵심 서비스 목 처리

아래 커스텀 액션처럼 커스텀 액션이 handler(ctx) 실행 안에서 Config Core Service를 필요로 한다면, @backstage/config 패키지 안의 ConfigReader 함수로 mockContext를 만들어 컨텍스트 객체를 목 처리할 수 있습니다.

// custom-action.tsimport { Config } from '@backstage/config';export const customActionRequiringConfigCoreService = (config: Config) => {  const fieldRequiringValueFromConfig = config.getString('app.service.url');  return createTemplateAction({    ...    async handler(ctx) {      // Some code requiring the config const      ctx.logger.info(fieldRequiringValueFromConfig);    }  })}
// custom-action.test.tsimport { ConfigReader } from '@backstage/config';import { customActionRequiringConfigCoreService } from './custom-action.ts';...const mockConfig = new ConfigReader({  app: {    service: {      url: 'https://api.service.io/graphql',      apiKeyId: '123',      apiKeySecret: '123abc',    },  },});...const action = customActionRequiringConfigCoreService(mockConfig);await action.handler({  ...mockContext})

Cache 핵심 서비스 목 처리

위의 Config Core Service 목 처리 섹션과 유사하게, 커스텀 액션이 함수 입력의 일부로 Cache Core Service 객체를 기대한다면, 다음으로 목 처리할 수 있습니다.

import { CacheService } from '@backstage/backend-plugin-api';const mockCacheServiceMethods = {  get: jest.fn(),  set: jest.fn(),  delete: jest.fn(),};const mockCacheService = mockCacheServiceMethods as unknown as CacheService;const action = customActionRequiringCacheCoreService(mockCacheService);...

더 알아보기 (Learn more)