/* eslint-disable @typescript-eslint/no-non-null-assertion */ import type express from 'express'; import * as client from './customer.js'; import {expect} from 'chai'; import {suite, test, before, after} from 'mocha'; import { CUSTOMER_PATH, CreateCustomerRequest, CreateCustomerResponse, } from '../server/api-types.js'; import {s, newFakeAppServer} from './test-helpers.js'; import type {FakeAppServer} from './test-helpers.js'; import {simpleFetch} from './simple-fetch-node.js'; suite('Client: Customer', () => { suite('createCustomer', () => { let fakeAppServer: FakeAppServer; before(async () => { fakeAppServer = await newFakeAppServer(CUSTOMER_PATH); }); after(() => { fakeAppServer.server!.close(); }); const goodReq: CreateCustomerRequest = { name: 'fritz', project: 'project', email: 'foo@example.com', commercial: true, acceptedTOS: true, }; // Test cases type TestCase = { desc: string; name: string; project: string | undefined; email: string; commercial: boolean; acceptedTOS: boolean; expReq: CreateCustomerRequest; status: number; resp: CreateCustomerResponse | string | undefined; expLicenseKey: string | undefined; }; const tests: TestCase[] = [ { desc: 'good request', name: 'fritz', project: 'project', email: 'foo@example.com', commercial: true, acceptedTOS: true, expReq: goodReq, status: 200, resp: {licenseKey: 'abc123'}, expLicenseKey: 'abc123', }, { desc: 'good request no project', name: 'fritz', project: undefined, email: 'foo@example.com', commercial: true, acceptedTOS: true, expReq: { name: 'fritz', email: 'foo@example.com', commercial: true, acceptedTOS: true, }, status: 200, resp: {licenseKey: 'abc123'}, expLicenseKey: 'abc123', }, { desc: 'throws an error', name: 'fritz', project: 'project', email: 'foo@example.com', commercial: true, acceptedTOS: true, expReq: goodReq, status: 500, resp: 'boom', expLicenseKey: '', }, ]; tests.forEach(t => { test(t.desc, async () => { fakeAppServer.handler = ( req: express.Request, res: express.Response, ) => { expect(req.method).to.equal('POST'); expect(req.header('accept')).to.match(/json/); expect(req.header('content-type')).to.match(/json/); expect(req.originalUrl).to.equal(CUSTOMER_PATH); expect(req.body).to.deep.equal( t.expReq, `${t.desc} expected ${s(t.expReq)}, got ${s(req.body)}`, ); res.status(t.status).json(t.resp); }; let got: string | undefined; // eslint-disable-next-line @typescript-eslint/no-explicit-any let gotError: any; try { got = await client.createCustomer( simpleFetch, fakeAppServer.url!, t.name, t.project, t.email, t.commercial, t.acceptedTOS, ); } catch (e) { gotError = e; } if (t.status !== 200) { expect(got).undefined; expect(gotError).instanceOf(Error); expect(gotError.message).to.match( new RegExp(t.resp as string), `'${gotError.message}' did not match ${t.resp}`, ); } else { expect(gotError).undefined; expect(got).to.equal(t.expLicenseKey); } }); }); }); });