@jest/globals#jest TypeScript Examples

The following examples show how to use @jest/globals#jest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: get-default.spec.ts    From leapp with Mozilla Public License 2.0 6 votes vote down vote up
describe("GetDefaultRegion", () => {
  test("run", async () => {
    const cliProviderService = { regionsService: { getDefaultAwsRegion: () => "defaultRegion" } } as any;

    const command = new GetDefaultRegion([], {} as any);
    (command as any).cliProviderService = cliProviderService;
    command.log = jest.fn();

    await command.run();

    expect(command.log).toHaveBeenCalledWith("defaultRegion");
  });
});
Example #2
Source File: githubstatus.test.ts    From ghaction-github-status with MIT License 6 votes vote down vote up
describe('summary', () => {
  test.each([['data-summary.json'], ['data-summary-2.json']])('given %p', async file => {
    jest.spyOn(githubstatus, 'summary').mockImplementation((): Promise<Summary> => {
      return <Promise<Summary>>(JSON.parse(
        fs.readFileSync(path.join(__dirname, 'fixtures', file), {
          encoding: 'utf8',
          flag: 'r'
        })
      ) as unknown);
    });
    const summary = await githubstatus.summary();
    expect(summary?.status.indicator).not.toEqual('');
    expect(summary?.components?.length).toBeGreaterThan(0);
  });
});
Example #3
Source File: context.test.ts    From ghaction-virustotal with MIT License 6 votes vote down vote up
describe('setOutput', () => {
  beforeEach(() => {
    process.stdout.write = jest.fn() as typeof process.stdout.write;
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput produces the correct command', () => {
    context.setOutput('some output', 'some value');
    assertWriteCalls([`::set-output name=some output::some value${os.EOL}`]);
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput handles bools', () => {
    context.setOutput('some output', false);
    assertWriteCalls([`::set-output name=some output::false${os.EOL}`]);
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput handles numbers', () => {
    context.setOutput('some output', 1.01);
    assertWriteCalls([`::set-output name=some output::1.01${os.EOL}`]);
  });
});
Example #4
Source File: buildx.test.ts    From bake-action with Apache License 2.0 6 votes vote down vote up
describe('isAvailable', () => {
  const execSpy = jest.spyOn(exec, 'getExecOutput');
  buildx.isAvailable();

  // eslint-disable-next-line jest/no-standalone-expect
  expect(execSpy).toHaveBeenCalledWith(`docker`, ['buildx'], {
    silent: true,
    ignoreReturnCode: true
  });
});
Example #5
Source File: buildx.test.ts    From build-push-action with Apache License 2.0 6 votes vote down vote up
describe('isAvailable', () => {
  const execSpy = jest.spyOn(exec, 'getExecOutput');
  buildx.isAvailable();

  // eslint-disable-next-line jest/no-standalone-expect
  expect(execSpy).toHaveBeenCalledWith(`docker`, ['buildx'], {
    silent: true,
    ignoreReturnCode: true
  });
});
Example #6
Source File: docker.test.ts    From login-action with Apache License 2.0 6 votes vote down vote up
test('loginStandard calls exec', async () => {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  const execSpy = jest.spyOn(exec, 'getExecOutput').mockImplementation(async () => {
    return {
      exitCode: expect.any(Number),
      stdout: expect.any(Function),
      stderr: expect.any(Function)
    };
  });

  const username = 'dbowie';
  const password = 'groundcontrol';
  const registry = 'https://ghcr.io';

  await loginStandard(registry, username, password);

  expect(execSpy).toHaveBeenCalledWith(`docker`, ['login', '--password-stdin', '--username', username, registry], {
    input: Buffer.from(password),
    silent: true,
    ignoreReturnCode: true
  });
});
Example #7
Source File: buildx.test.ts    From setup-buildx-action with Apache License 2.0 6 votes vote down vote up
describe('isAvailable', () => {
  const execSpy = jest.spyOn(exec, 'getExecOutput');
  buildx.isAvailable();

  // eslint-disable-next-line jest/no-standalone-expect
  expect(execSpy).toHaveBeenCalledWith(`docker`, ['buildx'], {
    silent: true,
    ignoreReturnCode: true
  });
});
Example #8
Source File: ApplicationStoreProviderTestUtils.tsx    From legend-studio with Apache License 2.0 6 votes vote down vote up
TEST__provideMockedApplicationStore = <
  T extends LegendApplicationConfig,
>(
  config: T,
  pluginManager: LegendApplicationPluginManager,
  customization?: {
    mock?: ApplicationStore<T>;
    navigator?: WebApplicationNavigator;
  },
): ApplicationStore<T> => {
  const value =
    customization?.mock ??
    new ApplicationStore(
      config,
      customization?.navigator ??
        new WebApplicationNavigator(createMemoryHistory()),
      pluginManager,
    );
  const MockedApplicationStoreProvider = require('./ApplicationStoreProvider.js'); // eslint-disable-line @typescript-eslint/no-unsafe-assignment
  MockedApplicationStoreProvider.useApplicationStore = jest.fn();
  MockedApplicationStoreProvider.useApplicationStore.mockReturnValue(value);
  return value;
}
Example #9
Source File: ledger.spec.ts    From formkit with MIT License 6 votes vote down vote up
describe('ledger tracking on single node', () => {
  it('automatically resolves when no matching ledger is found', () => {
    const node = createNode()
    expect(node.ledger.settled('party')).toBeInstanceOf(Promise)
  })

  it('does not resolve until ledger is settled', async () => {
    const braveHeart = createNode()
    braveHeart.ledger.count('braveheart')
    braveHeart.store.set(
      createMessage({
        key: 'freedom',
        type: 'braveheart',
      })
    )
    expect(braveHeart.ledger.value('braveheart')).toBe(1)
    const whenSettled = jest.fn()
    braveHeart.ledger.settled('braveheart').then(whenSettled)
    braveHeart.store.set(
      createMessage({
        key: 'freedom-2',
        type: 'braveheart',
      })
    )
    await nextTick()
    expect(whenSettled).toHaveBeenCalledTimes(0)
    braveHeart.store.remove('freedom')
    expect(whenSettled).toHaveBeenCalledTimes(0)
    braveHeart.store.remove('freedom-2')
    await nextTick()
    expect(whenSettled).toHaveBeenCalledTimes(1)
  })
})
Example #10
Source File: createLoggerTest.ts    From aloxide with Apache License 2.0 6 votes vote down vote up
createLoggerTest = (): Logger => {
  const logger = Logger.createLogger({
    name: 'test',
    level: 'debug',
  });

  logger.info = jest.fn(() => true);
  logger.debug = jest.fn(() => true);
  logger.warn = jest.fn(() => true);
  logger.error = jest.fn(() => true);

  return logger;
}
Example #11
Source File: framework.test.ts    From slice-machine with Apache License 2.0 6 votes vote down vote up
describe("framework.fancyName", () => {
  afterEach(() => {
    jest.resetAllMocks();
  });

  test("it should return a fancy name", () => {
    expect(FrameworkUtils.fancyName(Frameworks.gatsby)).toEqual("Gatsby");
  });

  test("it should return a Next.js for next (special case)", () => {
    expect(FrameworkUtils.fancyName(Frameworks.next)).toEqual("Next.js");
  });
});
Example #12
Source File: helpers.spec.ts    From homebridge-vieramatic with Apache License 2.0 5 votes vote down vote up
jest.setTimeout(30_000)
Example #13
Source File: list.spec.ts    From leapp with Mozilla Public License 2.0 5 votes vote down vote up
describe("ListIdpUrls", () => {
  const getTestCommand = (cliProviderService: any = null, argv: string[] = []): ListIdpUrls => {
    const command = new ListIdpUrls(argv, {} as any);
    (command as any).cliProviderService = cliProviderService;
    return command;
  };

  test("run", async () => {
    const command = getTestCommand();
    command.showIdpUrls = jest.fn();
    await command.run();

    expect(command.showIdpUrls).toHaveBeenCalled();
  });

  test("run - showIdpUrls throw an error", async () => {
    const command = getTestCommand();
    command.showIdpUrls = jest.fn(async () => {
      throw new Error("error");
    });
    try {
      await command.run();
    } catch (error) {
      expect(error).toEqual(new Error("error"));
    }
  });

  test("run - showIdpUrls throw an object", async () => {
    const command = getTestCommand();
    const errorToThrow = "string";
    command.showIdpUrls = jest.fn(async () => {
      throw errorToThrow;
    });
    try {
      await command.run();
    } catch (error) {
      expect(error).toEqual(new Error("Unknown error: string"));
    }
  });

  test("showIdpUrls", async () => {
    const idpUrls = [
      {
        url: "idpUrlsName",
      },
    ];
    const cliProviderService = {
      idpUrlsService: {
        getIdpUrls: () => idpUrls,
      },
    };

    const command = getTestCommand(cliProviderService);
    const tableSpy = jest.spyOn(CliUx.ux, "table").mockImplementation(() => null);

    await command.showIdpUrls();

    const expectedData = [
      {
        url: "idpUrlsName",
      },
    ];

    expect(tableSpy.mock.calls[0][0]).toEqual(expectedData);

    const expectedColumns = {
      id: { header: "ID", extended: true },
      url: { header: "Identity Provider URL" },
    };
    expect(tableSpy.mock.calls[0][1]).toEqual(expectedColumns);
  });
});
Example #14
Source File: runner.ts    From yarn-audit-fix with MIT License 5 votes vote down vote up
readFixture = (name: string): string =>
  (jest.requireActual('fs') as typeof fs).readFileSync(
    resolve(fixtures, name),
    {
      encoding: 'utf-8',
    },
  )
Example #15
Source File: githubstatus.test.ts    From ghaction-github-status with MIT License 5 votes vote down vote up
describe('status', () => {
  test.each([
    [
      'data-status.json',
      {
        description: 'Minor Service Outage',
        indicator: 'minor'
      } as Status,
      {
        id: 'kctbh9vrtdwd',
        name: 'GitHub',
        url: 'https://www.githubstatus.com',
        time_zone: 'Etc/UTC',
        updated_at: '2020-05-22T20:50:20.457Z'
      } as Page
    ],
    [
      'data-status-2.json',
      {
        description: 'Service Under Maintenance',
        indicator: 'maintenance'
      } as Status,
      {
        id: 'kctbh9vrtdwd',
        name: 'GitHub',
        url: 'https://www.githubstatus.com',
        time_zone: 'Etc/UTC',
        updated_at: '2020-12-17T00:54:37.709Z'
      } as Page
    ]
  ])('given %p', async (file, expStatus, expPage) => {
    jest.spyOn(githubstatus, 'status').mockImplementation((): Promise<Status> => {
      return <Promise<Status>>(JSON.parse(
        fs.readFileSync(path.join(__dirname, 'fixtures', file), {
          encoding: 'utf8',
          flag: 'r'
        })
      ) as unknown);
    });
    const status = await githubstatus.status();
    expect(status?.status).toEqual(expStatus);
    expect(status?.page).toEqual(expPage);
  });
});
Example #16
Source File: github.test.ts    From ghaction-virustotal with MIT License 5 votes vote down vote up
jest.spyOn(context, 'tmpDir').mockImplementation((): string => {
  const tmpDir = path.join('/tmp/.ghaction-virustotal-jest').split(path.sep).join(path.posix.sep);
  if (!fs.existsSync(tmpDir)) {
    fs.mkdirSync(tmpDir, {recursive: true});
  }
  return tmpDir;
});
Example #17
Source File: buildx.test.ts    From bake-action with Apache License 2.0 5 votes vote down vote up
jest.spyOn(context, 'tmpDir').mockImplementation((): string => {
  const tmpDir = path.join('/tmp/.docker-bake-jest').split(path.sep).join(path.posix.sep);
  if (!fs.existsSync(tmpDir)) {
    fs.mkdirSync(tmpDir, {recursive: true});
  }
  return tmpDir;
});
Example #18
Source File: buildx.test.ts    From build-push-action with Apache License 2.0 5 votes vote down vote up
jest.spyOn(context, 'tmpDir').mockImplementation((): string => {
  const tmpDir = path.join('/tmp/.docker-build-push-jest').split(path.sep).join(path.posix.sep);
  if (!fs.existsSync(tmpDir)) {
    fs.mkdirSync(tmpDir, {recursive: true});
  }
  return tmpDir;
});
Example #19
Source File: aws.test.ts    From login-action with Apache License 2.0 5 votes vote down vote up
mockEcrGetAuthToken = jest.fn()
Example #20
Source File: buildx.test.ts    From setup-buildx-action with Apache License 2.0 5 votes vote down vote up
jest.spyOn(context, 'tmpDir').mockImplementation((): string => {
  const tmpDir = path.join('/tmp/.docker-setup-buildx-jest').split(path.sep).join(path.posix.sep);
  if (!fs.existsSync(tmpDir)) {
    fs.mkdirSync(tmpDir, {recursive: true});
  }
  return tmpDir;
});
Example #21
Source File: PureLanguageHelper.test.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
afterEach(() => {
  // running all pending timers and switching to real timers using Jest
  // See https://testing-library.com/docs/using-fake-timers/
  jest.runOnlyPendingTimers();
  // NOTE: since `jest.useFakeTimers()` is global, it can leak across tests, we need to reset after every test
  jest.useRealTimers();
});
Example #22
Source File: handlers.spec.ts    From formkit with MIT License 5 votes vote down vote up
describe('vue error interception', () => {
  it('decodes E600', () => {
    const warning = jest.fn(() => {})
    const mock = jest.spyOn(global.console, 'warn').mockImplementation(warning)
    expect(() =>
      mount(FormKit, {
        props: {
          type: 'slick',
          name: 'foobar',
        },
        global: {
          plugins: [[plugin, defaultConfig]],
        },
      })
    ).toThrowError('Unknown input type "slick" ("foobar")')
    mock.mockReset()
  })

  it('decodes E601', () => {
    expect(() =>
      mount(FormKit, {
        props: {
          type: 'barfoo',
          name: 'bizbaz',
        },
        global: {
          plugins: [
            [
              plugin,
              defaultConfig({
                inputs: {
                  barfoo: {
                    type: 'input',
                  },
                },
              }),
            ],
          ],
        },
      })
    ).toThrowError(
      'Input definition "barfoo" is missing a schema or component property (bizbaz).'
    )
  })
})
Example #23
Source File: createLoggerTest.ts    From aloxide with Apache License 2.0 5 votes vote down vote up
createLoggerTest = (): Logger => ({
  info: jest.fn(),
  debug: jest.fn(),
  warn: jest.fn(),
  error: jest.fn(),
})