<!DOCTYPE html>
<link rel="help" href="https://github.com/WICG/WebOTP">
<title>Tests OTPCredential</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="./support/otpcredential-helper.js"></script>
<script>
'use strict';

promise_test(async t => {
  await expect(receive).andReturn(async () => {
      return {status: Status.kSuccess, otp: "ABC"};
  });

  let cred = await navigator.credentials.get({otp: {transport: ["sms"]}});

  assert_equals(cred.code, "ABC");
}, 'Basic usage');

promise_test(async t => {
  await expect(receive).andReturn(async () => {
      return {status: Status.kSuccess, otp: "ABC"};
  });
  await expect(receive).andReturn(async () => {
      return {status: Status.kSuccess, otp: "ABC2"};
  });

  let sms1 = navigator.credentials.get({otp: {transport: ["sms"]}});
  let sms2 = navigator.credentials.get({otp: {transport: ["sms"]}});

  let cred2= await sms2;
  let cred1 = await sms1;

  assert_equals(cred1.code, "ABC");
  assert_equals(cred2.code, "ABC2");
}, 'Handle multiple requests in different order.');

promise_test(async t => {
  await expect(receive).andReturn(async () => {
      return {status: Status.kCancelled};
  });
  await expect(receive).andReturn(async () => {
      return {status: Status.kSuccess, otp: "success"};
  });

  let cancelled_sms = navigator.credentials.get({otp: {transport: ["sms"]}});
  let successful_sms = navigator.credentials.get({otp: {transport: ["sms"]}});

  let successful_cred = await successful_sms;
  assert_equals(successful_cred.code, "success");

  try {
    await cancelled_sms;
    assert_unreached('Expected AbortError to be thrown.');
  } catch (error) {
    assert_equals(error.name, "AbortError");
  }
}, 'Handle multiple requests with success and error.');

promise_test(async t => {
  await expect(receive).andReturn(async () => {
      return {status: Status.kCancelled};
  });

  await promise_rejects_dom(t, 'AbortError', navigator.credentials.get(
    {otp: {transport: ["sms"]}}));
}, 'Deal with cancelled requests');

promise_test(async t => {
  const controller = new AbortController();
  const signal = controller.signal;

  controller.abort();
  await promise_rejects_dom(t, 'AbortError', navigator.credentials.get(
    {otp: {transport: ["sms"]}, signal: signal}));
}, 'Should abort request');

</script>
