From b8eb2140577ac0506fb25edd81c48f5a275b9fac Mon Sep 17 00:00:00 2001 From: Aras Abbasi Date: Wed, 24 Sep 2025 09:17:16 +0200 Subject: [PATCH] chore: use testcontext for mock tests --- test/mock-agent.js | 954 +++++++++------------ test/mock-call-history-log.js | 41 +- test/mock-call-history.js | 155 ++-- test/mock-client.js | 127 ++- test/mock-errors.js | 21 +- test/mock-interceptor-unused-assertions.js | 53 +- test/mock-interceptor.js | 97 ++- test/mock-pool.js | 103 ++- test/mock-scope.js | 33 +- test/mock-utils.js | 111 ++- 10 files changed, 762 insertions(+), 933 deletions(-) diff --git a/test/mock-agent.js b/test/mock-agent.js index 803933a67ec..f0b20e909e6 100644 --- a/test/mock-agent.js +++ b/test/mock-agent.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, after, describe } = require('node:test') const { createServer } = require('node:http') const { once } = require('node:events') @@ -18,74 +17,74 @@ const { MockCallHistory } = require('../lib/mock/mock-call-history') describe('MockAgent - constructor', () => { test('sets up mock agent', t => { - t = tspl(t, { plan: 1 }) - t.doesNotThrow(() => new MockAgent()) + t.plan(1) + t.assert.doesNotThrow(() => new MockAgent()) }) test('should implement the Dispatcher API', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() - t.ok(mockAgent instanceof Dispatcher) + t.assert.ok(mockAgent instanceof Dispatcher) }) test('sets up mock agent with single connection', t => { - t = tspl(t, { plan: 1 }) - t.doesNotThrow(() => new MockAgent({ connections: 1 })) + t.plan(1) + t.assert.doesNotThrow(() => new MockAgent({ connections: 1 })) }) test('should error passed agent is not valid', t => { - t = tspl(t, { plan: 2 }) - t.throws(() => new MockAgent({ agent: {} }), new InvalidArgumentError('Argument opts.agent must implement Agent')) - t.throws(() => new MockAgent({ agent: { dispatch: '' } }), new InvalidArgumentError('Argument opts.agent must implement Agent')) + t.plan(2) + t.assert.throws(() => new MockAgent({ agent: {} }), new InvalidArgumentError('Argument opts.agent must implement Agent')) + t.assert.throws(() => new MockAgent({ agent: { dispatch: '' } }), new InvalidArgumentError('Argument opts.agent must implement Agent')) }) test('should be able to specify the agent to mock', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const agent = new Agent() after(() => agent.close()) const mockAgent = new MockAgent({ agent }) - t.strictEqual(mockAgent[kAgent], agent) + t.assert.strictEqual(mockAgent[kAgent], agent) }) test('should disable call history by default', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockAgent = new MockAgent() after(() => mockAgent.close()) - t.strictEqual(mockAgent[kMockAgentIsCallHistoryEnabled], false) - t.strictEqual(mockAgent.getCallHistory(), undefined) + t.assert.strictEqual(mockAgent[kMockAgentIsCallHistoryEnabled], false) + t.assert.strictEqual(mockAgent.getCallHistory(), undefined) }) test('should enable call history if option is true', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockAgent = new MockAgent({ enableCallHistory: true }) after(() => mockAgent.close()) - t.strictEqual(mockAgent[kMockAgentIsCallHistoryEnabled], true) - t.ok(mockAgent.getCallHistory() instanceof MockCallHistory) + t.assert.strictEqual(mockAgent[kMockAgentIsCallHistoryEnabled], true) + t.assert.ok(mockAgent.getCallHistory() instanceof MockCallHistory) }) test('should disable call history if option is false', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) after(() => mockAgent.close()) const mockAgent = new MockAgent({ enableCallHistory: false }) - t.strictEqual(mockAgent[kMockAgentIsCallHistoryEnabled], false) - t.strictEqual(mockAgent.getCallHistory(), undefined) + t.assert.strictEqual(mockAgent[kMockAgentIsCallHistoryEnabled], false) + t.assert.strictEqual(mockAgent.getCallHistory(), undefined) }) test('should throw if enableCallHistory option is not a boolean', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) - t.throws(() => new MockAgent({ enableCallHistory: 'hello' }), new InvalidArgumentError('options.enableCallHistory must to be a boolean')) + t.assert.throws(() => new MockAgent({ enableCallHistory: 'hello' }), new InvalidArgumentError('options.enableCallHistory must to be a boolean')) }) }) describe('MockAgent - enableCallHistory', () => { test('should enable call history and add call history log', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockAgent = new MockAgent() setGlobalDispatcher(mockAgent) @@ -99,21 +98,19 @@ describe('MockAgent - enableCallHistory', () => { await fetch('http://localhost:9999/foo') - t.strictEqual(mockAgent.getCallHistory()?.calls()?.length, undefined) + t.assert.strictEqual(mockAgent.getCallHistory()?.calls()?.length, undefined) mockAgent.enableCallHistory() await request('http://localhost:9999/foo') - t.strictEqual(mockAgent.getCallHistory()?.calls()?.length, 1) - - await t.completed + t.assert.strictEqual(mockAgent.getCallHistory()?.calls()?.length, 1) }) }) describe('MockAgent - disableCallHistory', () => { test('should disable call history and not add call history log', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockAgent = new MockAgent({ enableCallHistory: true }) setGlobalDispatcher(mockAgent) @@ -127,21 +124,19 @@ describe('MockAgent - disableCallHistory', () => { await request('http://localhost:9999/foo') - t.strictEqual(mockAgent.getCallHistory()?.calls()?.length, 1) + t.assert.strictEqual(mockAgent.getCallHistory()?.calls()?.length, 1) mockAgent.disableCallHistory() await request('http://localhost:9999/foo') - t.strictEqual(mockAgent.getCallHistory()?.calls()?.length, 1) - - await t.completed + t.assert.strictEqual(mockAgent.getCallHistory()?.calls()?.length, 1) }) }) describe('MockAgent - get', () => { test('should return MockClient', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -149,11 +144,11 @@ describe('MockAgent - get', () => { after(() => mockAgent.close()) const mockClient = mockAgent.get(baseUrl) - t.ok(mockClient instanceof MockClient) + t.assert.ok(mockClient instanceof MockClient) }) test('should return MockPool', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -161,11 +156,11 @@ describe('MockAgent - get', () => { after(() => mockAgent.close()) const mockPool = mockAgent.get(baseUrl) - t.ok(mockPool instanceof MockPool) + t.assert.ok(mockPool instanceof MockPool) }) test('should return the same instance if already created', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -174,13 +169,13 @@ describe('MockAgent - get', () => { const mockPool1 = mockAgent.get(baseUrl) const mockPool2 = mockAgent.get(baseUrl) - t.strictEqual(mockPool1, mockPool2) + t.assert.strictEqual(mockPool1, mockPool2) }) }) describe('MockAgent - dispatch', () => { test('should call the dispatch method of the MockPool', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -194,7 +189,7 @@ describe('MockAgent - dispatch', () => { method: 'GET' }).reply(200, 'hello') - t.doesNotThrow(() => mockAgent.dispatch({ + t.assert.doesNotThrow(() => mockAgent.dispatch({ origin: baseUrl, path: '/foo', method: 'GET' @@ -207,7 +202,7 @@ describe('MockAgent - dispatch', () => { }) test('should call the dispatch method of the MockClient', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -221,7 +216,7 @@ describe('MockAgent - dispatch', () => { method: 'GET' }).reply(200, 'hello') - t.doesNotThrow(() => mockAgent.dispatch({ + t.assert.doesNotThrow(() => mockAgent.dispatch({ origin: baseUrl, path: '/foo', method: 'GET' @@ -235,7 +230,7 @@ describe('MockAgent - dispatch', () => { }) test('MockAgent - .close should clean up registered pools', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const baseUrl = 'http://localhost:9999' @@ -243,19 +238,17 @@ test('MockAgent - .close should clean up registered pools', async (t) => { // Register a pool const mockPool = mockAgent.get(baseUrl) - t.ok(mockPool instanceof MockPool) + t.assert.ok(mockPool instanceof MockPool) - t.strictEqual(mockPool[kConnected], 1) - t.strictEqual(mockAgent[kClients].size, 1) + t.assert.strictEqual(mockPool[kConnected], 1) + t.assert.strictEqual(mockAgent[kClients].size, 1) await mockAgent.close() - t.strictEqual(mockPool[kConnected], 0) - t.strictEqual(mockAgent[kClients].size, 0) - - await t.completed + t.assert.strictEqual(mockPool[kConnected], 0) + t.assert.strictEqual(mockAgent[kClients].size, 0) }) test('MockAgent - .close should clean up registered clients', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const baseUrl = 'http://localhost:9999' @@ -263,24 +256,22 @@ test('MockAgent - .close should clean up registered clients', async (t) => { // Register a pool const mockClient = mockAgent.get(baseUrl) - t.ok(mockClient instanceof MockClient) + t.assert.ok(mockClient instanceof MockClient) - t.strictEqual(mockClient[kConnected], 1) - t.strictEqual(mockAgent[kClients].size, 1) + t.assert.strictEqual(mockClient[kConnected], 1) + t.assert.strictEqual(mockAgent[kClients].size, 1) await mockAgent.close() - t.strictEqual(mockClient[kConnected], 0) - t.strictEqual(mockAgent[kClients].size, 0) - - await t.completed + t.assert.strictEqual(mockClient[kConnected], 0) + t.assert.strictEqual(mockAgent[kClients].size, 0) }) test('MockAgent - [kClients] should match encapsulated agent', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -300,18 +291,16 @@ test('MockAgent - [kClients] should match encapsulated agent', async (t) => { }).reply(200, 'hello') // The MockAgent should encapsulate the input agent clients - t.strictEqual(mockAgent[kClients].size, agent[kClients].size) - - await t.completed + t.assert.strictEqual(mockAgent[kClients].size, agent[kClients].size) }) test('MockAgent - basic intercept with MockAgent.request', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -338,25 +327,23 @@ test('MockAgent - basic intercept with MockAgent.request', async (t) => { method: 'POST', body: 'form1=data1&form2=data2' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') - t.deepStrictEqual(trailers, { 'content-md5': 'test' }) + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') + t.assert.deepStrictEqual(trailers, { 'content-md5': 'test' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) - - await t.completed }) test('MockAgent - basic intercept with request', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -382,25 +369,23 @@ test('MockAgent - basic intercept with request', async (t) => { method: 'POST', body: 'form1=data1&form2=data2' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') - t.deepStrictEqual(trailers, { 'content-md5': 'test' }) + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') + t.assert.deepStrictEqual(trailers, { 'content-md5': 'test' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) - - await t.completed }) test('MockAgent - should support local agents', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -429,25 +414,23 @@ test('MockAgent - should support local agents', async (t) => { body: 'form1=data1&form2=data2', dispatcher: mockAgent }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') - t.deepStrictEqual(trailers, { 'content-md5': 'test' }) + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') + t.assert.deepStrictEqual(trailers, { 'content-md5': 'test' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) - - await t.completed }) test('MockAgent - should support specifying custom agents to mock', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -477,25 +460,23 @@ test('MockAgent - should support specifying custom agents to mock', async (t) => method: 'POST', body: 'form1=data1&form2=data2' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') - t.deepStrictEqual(trailers, { 'content-md5': 'test' }) + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') + t.assert.deepStrictEqual(trailers, { 'content-md5': 'test' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) - - await t.completed }) test('MockAgent - basic Client intercept with request', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -523,25 +504,23 @@ test('MockAgent - basic Client intercept with request', async (t) => { method: 'POST', body: 'form1=data1&form2=data2' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') - t.deepStrictEqual(trailers, { 'content-md5': 'test' }) + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') + t.assert.deepStrictEqual(trailers, { 'content-md5': 'test' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) - - await t.completed }) test('MockAgent - basic intercept with multiple pools', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -576,25 +555,23 @@ test('MockAgent - basic intercept with multiple pools', async (t) => { method: 'POST', body: 'form1=data1&form2=data2' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') - t.deepStrictEqual(trailers, { 'content-md5': 'test' }) + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') + t.assert.deepStrictEqual(trailers, { 'content-md5': 'test' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar-1' }) - - await t.completed }) test('MockAgent - should handle multiple responses for an interceptor', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -627,11 +604,11 @@ test('MockAgent - should handle multiple responses for an interceptor', async (t const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'POST' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) } @@ -640,24 +617,22 @@ test('MockAgent - should handle multiple responses for an interceptor', async (t const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'POST' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { hello: 'there' }) } - - await t.completed }) test('MockAgent - should call original Pool dispatch if request not found', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.strictEqual(req.url, '/foo') - t.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.url, '/foo') + t.assert.strictEqual(req.method, 'GET') res.setHeader('content-type', 'text/plain') res.end('hello') }) @@ -674,21 +649,19 @@ test('MockAgent - should call original Pool dispatch if request not found', asyn const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'text/plain') + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'text/plain') const response = await getResponse(body) - t.strictEqual(response, 'hello') - - await t.completed + t.assert.strictEqual(response, 'hello') }) test('MockAgent - should call original Client dispatch if request not found', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.strictEqual(req.url, '/foo') - t.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.url, '/foo') + t.assert.strictEqual(req.method, 'GET') res.setHeader('content-type', 'text/plain') res.end('hello') }) @@ -705,22 +678,20 @@ test('MockAgent - should call original Client dispatch if request not found', as const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'text/plain') + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'text/plain') const response = await getResponse(body) - t.strictEqual(response, 'hello') - - await t.completed + t.assert.strictEqual(response, 'hello') }) test('MockAgent - should handle string responses', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -741,12 +712,10 @@ test('MockAgent - should handle string responses', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'POST' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'hello') - - await t.completed + t.assert.strictEqual(response, 'hello') }) test('MockAgent - should handle basic concurrency for requests', { jobs: 5 }, async (t) => { @@ -756,7 +725,7 @@ test('MockAgent - should handle basic concurrency for requests', { jobs: 5 }, as await Promise.all([...Array(5).keys()].map(idx => test(`concurrent job (${idx})`, async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const baseUrl = 'http://localhost:9999' @@ -769,27 +738,23 @@ test('MockAgent - should handle basic concurrency for requests', { jobs: 5 }, as const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'POST' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: `bar ${idx}` }) - - await t.completed }) )) - - await t.completed }) test('MockAgent - handle delays to simulate work', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -812,23 +777,21 @@ test('MockAgent - handle delays to simulate work', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'POST' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'hello') + t.assert.strictEqual(response, 'hello') const elapsedInMs = Math.ceil(process.hrtime(start)[1] / 1e6) - t.ok(elapsedInMs >= 50, `Elapsed time is not greater than 50ms: ${elapsedInMs}`) - - await t.completed + t.assert.ok(elapsedInMs >= 50, `Elapsed time is not greater than 50ms: ${elapsedInMs}`) }) test('MockAgent - should persist requests', async (t) => { - t = tspl(t, { plan: 8 }) + t.plan(8) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -857,12 +820,12 @@ test('MockAgent - should persist requests', async (t) => { method: 'POST', body: 'form1=data1&form2=data2' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') - t.deepStrictEqual(trailers, { 'content-md5': 'test' }) + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') + t.assert.deepStrictEqual(trailers, { 'content-md5': 'test' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) } @@ -872,21 +835,19 @@ test('MockAgent - should persist requests', async (t) => { method: 'POST', body: 'form1=data1&form2=data2' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') - t.deepStrictEqual(trailers, { 'content-md5': 'test' }) + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') + t.assert.deepStrictEqual(trailers, { 'content-md5': 'test' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) } - - await t.completed }) test('MockAgent - getCallHistory with no name parameter should return the agent call history', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent({ enableCallHistory: true }) setGlobalDispatcher(mockAgent) @@ -898,13 +859,11 @@ test('MockAgent - getCallHistory with no name parameter should return the agent method: 'GET' }).reply(200, 'foo') - t.ok(mockAgent.getCallHistory() instanceof MockCallHistory) - - await t.completed + t.assert.ok(mockAgent.getCallHistory() instanceof MockCallHistory) }) test('MockAgent - getCallHistory with request should return the call history instance with history log', async (t) => { - t = tspl(t, { plan: 9 }) + t.plan(9) const mockAgent = new MockAgent({ enableCallHistory: true }) setGlobalDispatcher(mockAgent) @@ -917,7 +876,7 @@ test('MockAgent - getCallHistory with request should return the call history ins method: 'POST' }).reply(200, 'foo') - t.ok(mockAgent.getCallHistory()?.calls().length === 0) + t.assert.ok(mockAgent.getCallHistory()?.calls().length === 0) const path = '/foo' const url = new URL(path, baseUrl) @@ -928,20 +887,18 @@ test('MockAgent - getCallHistory with request should return the call history ins await request(url, { method, query, body: JSON.stringify(body), headers }) - t.ok(mockAgent.getCallHistory()?.calls().length === 1) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.body, JSON.stringify(body)) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.headers, headers) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.method, method) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.origin, baseUrl) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.path, path) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.fullUrl, `${url.toString()}?${new URLSearchParams(query).toString()}`) - t.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.searchParams, { a: '1' }) - - await t.completed + t.assert.ok(mockAgent.getCallHistory()?.calls().length === 1) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.body, JSON.stringify(body)) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.headers, headers) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.method, method) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.origin, baseUrl) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.path, path) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.fullUrl, `${url.toString()}?${new URLSearchParams(query).toString()}`) + t.assert.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.searchParams, { a: '1' }) }) test('MockAgent - getCallHistory with fetch should return the call history instance with history log', async (t) => { - t = tspl(t, { plan: 9 }) + t.plan(9) const mockAgent = new MockAgent({ enableCallHistory: true }) setGlobalDispatcher(mockAgent) @@ -954,7 +911,7 @@ test('MockAgent - getCallHistory with fetch should return the call history insta method: 'POST' }).reply(200, 'foo') - t.ok(mockAgent.getCallHistory()?.calls().length === 0) + t.assert.ok(mockAgent.getCallHistory()?.calls().length === 0) const path = '/foo' const url = new URL(path, baseUrl) @@ -966,9 +923,9 @@ test('MockAgent - getCallHistory with fetch should return the call history insta await fetch(url, { method, query, body: JSON.stringify(body), headers }) - t.ok(mockAgent.getCallHistory()?.calls().length === 1) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.body, JSON.stringify(body)) - t.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.headers, { + t.assert.ok(mockAgent.getCallHistory()?.calls().length === 1) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.body, JSON.stringify(body)) + t.assert.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.headers, { ...headers, 'accept-encoding': 'gzip, deflate', 'content-length': '16', @@ -978,17 +935,15 @@ test('MockAgent - getCallHistory with fetch should return the call history insta 'user-agent': 'undici', accept: '*/*' }) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.method, method) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.origin, baseUrl) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.path, url.pathname) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.fullUrl, url.toString()) - t.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.searchParams, { a: '1' }) - - await t.completed + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.method, method) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.origin, baseUrl) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.path, url.pathname) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.fullUrl, url.toString()) + t.assert.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.searchParams, { a: '1' }) }) test('MockAgent - getCallHistory with fetch with a minimal configuration should register call history log', async (t) => { - t = tspl(t, { plan: 11 }) + t.plan(11) const mockAgent = new MockAgent({ enableCallHistory: true }) setGlobalDispatcher(mockAgent) @@ -1005,29 +960,27 @@ test('MockAgent - getCallHistory with fetch with a minimal configuration should await fetch(url) - t.ok(mockAgent.getCallHistory()?.calls().length === 1) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.body, null) - t.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.headers, { + t.assert.ok(mockAgent.getCallHistory()?.calls().length === 1) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.body, null) + t.assert.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.headers, { 'accept-encoding': 'gzip, deflate', 'accept-language': '*', 'sec-fetch-mode': 'cors', 'user-agent': 'undici', accept: '*/*' }) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.method, 'GET') - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.origin, baseUrl) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.path, path) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.fullUrl, baseUrl + path) - t.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.searchParams, {}) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.host, 'localhost:9999') - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.port, '9999') - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.protocol, 'http:') - - await t.completed + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.method, 'GET') + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.origin, baseUrl) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.path, path) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.fullUrl, baseUrl + path) + t.assert.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.searchParams, {}) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.host, 'localhost:9999') + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.port, '9999') + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.protocol, 'http:') }) test('MockAgent - getCallHistory with request with a minimal configuration should register call history log', async (t) => { - t = tspl(t, { plan: 11 }) + t.plan(11) const mockAgent = new MockAgent({ enableCallHistory: true }) setGlobalDispatcher(mockAgent) @@ -1044,23 +997,21 @@ test('MockAgent - getCallHistory with request with a minimal configuration shoul await request(url) - t.ok(mockAgent.getCallHistory()?.calls().length === 1) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.body, undefined) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.headers, undefined) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.method, 'GET') - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.origin, baseUrl) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.path, path) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.fullUrl, baseUrl + path) - t.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.searchParams, {}) - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.host, 'localhost:9999') - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.port, '9999') - t.strictEqual(mockAgent.getCallHistory()?.lastCall()?.protocol, 'http:') - - await t.completed + t.assert.ok(mockAgent.getCallHistory()?.calls().length === 1) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.body, undefined) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.headers, undefined) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.method, 'GET') + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.origin, baseUrl) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.path, path) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.fullUrl, baseUrl + path) + t.assert.deepStrictEqual(mockAgent.getCallHistory()?.lastCall()?.searchParams, {}) + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.host, 'localhost:9999') + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.port, '9999') + t.assert.strictEqual(mockAgent.getCallHistory()?.lastCall()?.protocol, 'http:') }) test('MockAgent - clearCallHistory should clear call history logs', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const mockAgent = new MockAgent({ enableCallHistory: true }) setGlobalDispatcher(mockAgent) @@ -1073,7 +1024,7 @@ test('MockAgent - clearCallHistory should clear call history logs', async (t) => method: 'POST' }).reply(200, 'foo').persist() - t.ok(mockAgent.getCallHistory()?.calls().length === 0) + t.assert.ok(mockAgent.getCallHistory()?.calls().length === 0) const path = '/foo' const url = new URL(path, baseUrl) @@ -1087,22 +1038,20 @@ test('MockAgent - clearCallHistory should clear call history logs', async (t) => await request(url, { method, query, body: JSON.stringify(body), headers }) await request(url, { method, query, body: JSON.stringify(body), headers }) - t.ok(mockAgent.getCallHistory()?.calls().length === 4) + t.assert.ok(mockAgent.getCallHistory()?.calls().length === 4) mockAgent.clearCallHistory() - t.ok(mockAgent.getCallHistory()?.calls().length === 0) - - await t.completed + t.assert.ok(mockAgent.getCallHistory()?.calls().length === 0) }) test('MockAgent - handle persists with delayed requests', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1124,32 +1073,30 @@ test('MockAgent - handle persists with delayed requests', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'POST' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'hello') + t.assert.strictEqual(response, 'hello') } { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'POST' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'hello') + t.assert.strictEqual(response, 'hello') } - - await t.completed }) test('MockAgent - calling close on a mock pool should not affect other mock pools', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1183,32 +1130,30 @@ test('MockAgent - calling close on a mock pool should not affect other mock pool const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') + t.assert.strictEqual(response, 'foo') } { const { statusCode, body } = await request(`${baseUrl}/bar`, { method: 'POST' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'bar') + t.assert.strictEqual(response, 'bar') } - - await t.completed }) test('MockAgent - close removes all registered mock clients', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1226,19 +1171,17 @@ test('MockAgent - close removes all registered mock clients', async (t) => { }).reply(200, 'foo') await mockAgent.close() - t.strictEqual(mockAgent[kClients].size, 0) + t.assert.strictEqual(mockAgent[kClients].size, 0) try { await request(`${baseUrl}/foo`, { method: 'GET' }) } catch (err) { - t.ok(err instanceof ClientDestroyedError) + t.assert.ok(err instanceof ClientDestroyedError) } - - await t.completed }) test('MockAgent - close clear all registered mock call history logs', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockAgent = new MockAgent({ enableCallHistory: true }) setGlobalDispatcher(mockAgent) @@ -1252,22 +1195,20 @@ test('MockAgent - close clear all registered mock call history logs', async (t) await request('http://localhost:9999/foo') - t.strictEqual(mockAgent.getCallHistory().calls().length, 1) + t.assert.strictEqual(mockAgent.getCallHistory().calls().length, 1) await mockAgent.close() - t.strictEqual(mockAgent.getCallHistory().calls().length, 0) - - await t.completed + t.assert.strictEqual(mockAgent.getCallHistory().calls().length, 0) }) test('MockAgent - close removes all registered mock pools', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1285,24 +1226,22 @@ test('MockAgent - close removes all registered mock pools', async (t) => { }).reply(200, 'foo') await mockAgent.close() - t.strictEqual(mockAgent[kClients].size, 0) + t.assert.strictEqual(mockAgent[kClients].size, 0) try { await request(`${baseUrl}/foo`, { method: 'GET' }) } catch (err) { - t.ok(err instanceof ClientDestroyedError) + t.assert.ok(err instanceof ClientDestroyedError) } - - await t.completed }) test('MockAgent - should handle replyWithError', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1320,17 +1259,15 @@ test('MockAgent - should handle replyWithError', async (t) => { method: 'GET' }).replyWithError(new Error('kaboom')) - await t.rejects(request(`${baseUrl}/foo`, { method: 'GET' }), new Error('kaboom')) - - await t.completed + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET' }), new Error('kaboom')) }) test('MockAgent - should support setting a reply to respond a set amount of times', async (t) => { - t = tspl(t, { plan: 9 }) + t.plan(9) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.strictEqual(req.url, '/foo') - t.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.url, '/foo') + t.assert.strictEqual(req.method, 'GET') res.setHeader('content-type', 'text/plain') res.end('hello') }) @@ -1352,39 +1289,37 @@ test('MockAgent - should support setting a reply to respond a set amount of time { const { statusCode, body } = await request(`${baseUrl}/foo`) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') + t.assert.strictEqual(response, 'foo') } { const { statusCode, body } = await request(`${baseUrl}/foo`) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') + t.assert.strictEqual(response, 'foo') } { const { statusCode, headers, body } = await request(`${baseUrl}/foo`) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'text/plain') + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'text/plain') const response = await getResponse(body) - t.strictEqual(response, 'hello') + t.assert.strictEqual(response, 'hello') } - - await t.completed }) test('MockAgent - persist overrides times', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1406,41 +1341,39 @@ test('MockAgent - persist overrides times', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') + t.assert.strictEqual(response, 'foo') } { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') + t.assert.strictEqual(response, 'foo') } { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') + t.assert.strictEqual(response, 'foo') } - - await t.completed }) test('MockAgent - matcher should not find mock dispatch if path is of unsupported type', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.strictEqual(req.url, '/foo') - t.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.url, '/foo') + t.assert.strictEqual(req.method, 'GET') res.end('hello') }) after(() => server.close()) @@ -1462,21 +1395,19 @@ test('MockAgent - matcher should not find mock dispatch if path is of unsupporte const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'hello') - - await t.completed + t.assert.strictEqual(response, 'hello') }) test('MockAgent - should match path with regex', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1498,32 +1429,30 @@ test('MockAgent - should match path with regex', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') + t.assert.strictEqual(response, 'foo') } { const { statusCode, body } = await request(`${baseUrl}/hello/foobar`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') + t.assert.strictEqual(response, 'foo') } - - await t.completed }) test('MockAgent - should match path with function', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1544,21 +1473,19 @@ test('MockAgent - should match path with function', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - should match method with regex', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1579,21 +1506,19 @@ test('MockAgent - should match method with regex', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - should match method with function', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1614,21 +1539,19 @@ test('MockAgent - should match method with function', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - should match body with regex', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1651,21 +1574,19 @@ test('MockAgent - should match body with regex', async (t) => { method: 'GET', body: 'hello=there' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - should match body with function', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1688,20 +1609,18 @@ test('MockAgent - should match body with function', async (t) => { method: 'GET', body: 'hello=there' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - should match headers with string', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1726,18 +1645,18 @@ test('MockAgent - should match headers with string', async (t) => { // Disable net connect so we can make sure it matches properly mockAgent.disableNetConnect() - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET' }), MockNotMatchedError, 'should reject with MockNotMatchedError') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: { foo: 'bar' } }), MockNotMatchedError, 'should reject with MockNotMatchedError') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: { foo: 'bar', @@ -1745,7 +1664,7 @@ test('MockAgent - should match headers with string', async (t) => { } }), MockNotMatchedError, 'should reject with MockNotMatchedError') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: { foo: 'bar', @@ -1762,20 +1681,18 @@ test('MockAgent - should match headers with string', async (t) => { Host: 'example.com' } }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - should match headers with regex', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1800,18 +1717,18 @@ test('MockAgent - should match headers with regex', async (t) => { // Disable net connect so we can make sure it matches properly mockAgent.disableNetConnect() - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET' }), MockNotMatchedError, 'should reject with MockNotMatchedError') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: { foo: 'bar' } }), MockNotMatchedError, 'should reject with MockNotMatchedError') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: { foo: 'bar', @@ -1819,7 +1736,7 @@ test('MockAgent - should match headers with regex', async (t) => { } }), MockNotMatchedError, 'should reject with MockNotMatchedError') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: { foo: 'bar', @@ -1836,20 +1753,18 @@ test('MockAgent - should match headers with regex', async (t) => { Host: 'example.com' } }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - should match headers with function', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1874,18 +1789,18 @@ test('MockAgent - should match headers with function', async (t) => { // Disable net connect so we can make sure it matches properly mockAgent.disableNetConnect() - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET' }), MockNotMatchedError, 'should reject with MockNotMatchedError') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: { foo: 'bar' } }), MockNotMatchedError, 'should reject with MockNotMatchedError') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: { foo: 'bar', @@ -1893,7 +1808,7 @@ test('MockAgent - should match headers with function', async (t) => { } }), MockNotMatchedError, 'should reject with MockNotMatchedError') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: { foo: 'bar', @@ -1910,21 +1825,19 @@ test('MockAgent - should match headers with function', async (t) => { Host: 'example.com' } }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - should match url with regex', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1945,21 +1858,19 @@ test('MockAgent - should match url with regex', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - should match url with function', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -1980,21 +1891,19 @@ test('MockAgent - should match url with function', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - handle default reply headers', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -2015,25 +1924,23 @@ test('MockAgent - handle default reply headers', async (t) => { const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.deepStrictEqual(headers, { + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(headers, { foo: 'bar', hello: 'there' }) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - handle default reply trailers', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -2054,25 +1961,23 @@ test('MockAgent - handle default reply trailers', async (t) => { const { statusCode, trailers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.deepStrictEqual(trailers, { + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(trailers, { foo: 'bar', hello: 'there' }) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - return calculated content-length if specified', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -2093,25 +1998,23 @@ test('MockAgent - return calculated content-length if specified', async (t) => { const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.deepStrictEqual(headers, { + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(headers, { hello: 'there', 'content-length': '3' }) const response = await getResponse(body) - t.strictEqual(response, 'foo') - - await t.completed + t.assert.strictEqual(response, 'foo') }) test('MockAgent - return calculated content-length for object response if specified', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') + t.assert.fail('should not be called') }) after(() => server.close()) @@ -2132,24 +2035,22 @@ test('MockAgent - return calculated content-length for object response if specif const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.deepStrictEqual(headers, { + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(headers, { hello: 'there', 'content-length': '13' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { foo: 'bar' }) - - await t.completed + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) }) test('MockAgent - should activate and deactivate mock clients', async (t) => { - t = tspl(t, { plan: 9 }) + t.plan(9) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.strictEqual(req.url, '/foo') - t.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.url, '/foo') + t.assert.strictEqual(req.method, 'GET') res.setHeader('content-type', 'text/plain') res.end('hello') }) @@ -2173,10 +2074,10 @@ test('MockAgent - should activate and deactivate mock clients', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') + t.assert.strictEqual(response, 'foo') } mockAgent.deactivate() @@ -2185,11 +2086,11 @@ test('MockAgent - should activate and deactivate mock clients', async (t) => { const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'text/plain') + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'text/plain') const response = await getResponse(body) - t.strictEqual(response, 'hello') + t.assert.strictEqual(response, 'hello') } mockAgent.activate() @@ -2198,21 +2099,19 @@ test('MockAgent - should activate and deactivate mock clients', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.strictEqual(response, 'foo') + t.assert.strictEqual(response, 'foo') } - - await t.completed }) test('MockAgent - enableNetConnect should allow all original dispatches to be called if dispatch not found', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.strictEqual(req.url, '/foo') - t.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.url, '/foo') + t.assert.strictEqual(req.method, 'GET') res.setHeader('content-type', 'text/plain') res.end('hello') }) @@ -2237,21 +2136,19 @@ test('MockAgent - enableNetConnect should allow all original dispatches to be ca const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'text/plain') + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'text/plain') const response = await getResponse(body) - t.strictEqual(response, 'hello') - - await t.completed + t.assert.strictEqual(response, 'hello') }) test('MockAgent - enableNetConnect with a host string should allow all original dispatches to be called if mockDispatch not found', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.strictEqual(req.url, '/foo') - t.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.url, '/foo') + t.assert.strictEqual(req.method, 'GET') res.setHeader('content-type', 'text/plain') res.end('hello') }) @@ -2276,21 +2173,19 @@ test('MockAgent - enableNetConnect with a host string should allow all original const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'text/plain') + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'text/plain') const response = await getResponse(body) - t.strictEqual(response, 'hello') - - await t.completed + t.assert.strictEqual(response, 'hello') }) test('MockAgent - enableNetConnect when called with host string multiple times should allow all original dispatches to be called if mockDispatch not found', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.strictEqual(req.url, '/foo') - t.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.url, '/foo') + t.assert.strictEqual(req.method, 'GET') res.setHeader('content-type', 'text/plain') res.end('hello') }) @@ -2316,21 +2211,19 @@ test('MockAgent - enableNetConnect when called with host string multiple times s const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'text/plain') + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'text/plain') const response = await getResponse(body) - t.strictEqual(response, 'hello') - - await t.completed + t.assert.strictEqual(response, 'hello') }) test('MockAgent - enableNetConnect with a host regex should allow all original dispatches to be called if mockDispatch not found', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.strictEqual(req.url, '/foo') - t.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.url, '/foo') + t.assert.strictEqual(req.method, 'GET') res.setHeader('content-type', 'text/plain') res.end('hello') }) @@ -2355,21 +2248,19 @@ test('MockAgent - enableNetConnect with a host regex should allow all original d const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'text/plain') + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'text/plain') const response = await getResponse(body) - t.strictEqual(response, 'hello') - - await t.completed + t.assert.strictEqual(response, 'hello') }) test('MockAgent - enableNetConnect with a function should allow all original dispatches to be called if mockDispatch not found', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.strictEqual(req.url, '/foo') - t.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.url, '/foo') + t.assert.strictEqual(req.method, 'GET') res.setHeader('content-type', 'text/plain') res.end('hello') }) @@ -2394,17 +2285,15 @@ test('MockAgent - enableNetConnect with a function should allow all original dis const { statusCode, headers, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'text/plain') + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'text/plain') const response = await getResponse(body) - t.strictEqual(response, 'hello') - - await t.completed + t.assert.strictEqual(response, 'hello') }) test('MockAgent - enableNetConnect with an unknown input should throw', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() setGlobalDispatcher(mockAgent) @@ -2416,16 +2305,14 @@ test('MockAgent - enableNetConnect with an unknown input should throw', async (t method: 'GET' }).reply(200, 'foo') - t.throws(() => mockAgent.enableNetConnect({}), new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')) - - await t.completed + t.assert.throws(() => mockAgent.enableNetConnect({}), new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')) }) test('MockAgent - enableNetConnect should throw if dispatch not matched for path and the origin was not allowed by net connect', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.fail('should not be called') + t.assert.fail('should not be called') res.end('should not be called') }) after(() => server.close()) @@ -2446,18 +2333,16 @@ test('MockAgent - enableNetConnect should throw if dispatch not matched for path mockAgent.enableNetConnect('example.com:9999') - await t.rejects(request(`${baseUrl}/wrong`, { + await t.assert.rejects(request(`${baseUrl}/wrong`, { method: 'GET' }), new MockNotMatchedError(`Mock dispatch not matched for path '/wrong': subsequent request to origin ${baseUrl} was not allowed (net.connect is not enabled for this origin)`)) - - await t.completed }) test('MockAgent - enableNetConnect should throw if dispatch not matched for method and the origin was not allowed by net connect', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.fail('should not be called') + t.assert.fail('should not be called') res.end('should not be called') }) after(() => server.close()) @@ -2478,18 +2363,16 @@ test('MockAgent - enableNetConnect should throw if dispatch not matched for meth mockAgent.enableNetConnect('example.com:9999') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'WRONG' }), new MockNotMatchedError(`Mock dispatch not matched for method 'WRONG' on path '/foo': subsequent request to origin ${baseUrl} was not allowed (net.connect is not enabled for this origin)`)) - - await t.completed }) test('MockAgent - enableNetConnect should throw if dispatch not matched for body and the origin was not allowed by net connect', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.fail('should not be called') + t.assert.fail('should not be called') res.end('should not be called') }) after(() => server.close()) @@ -2511,19 +2394,17 @@ test('MockAgent - enableNetConnect should throw if dispatch not matched for body mockAgent.enableNetConnect('example.com:9999') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', body: 'wrong' }), new MockNotMatchedError(`Mock dispatch not matched for body 'wrong' on path '/foo': subsequent request to origin ${baseUrl} was not allowed (net.connect is not enabled for this origin)`)) - - await t.completed }) test('MockAgent - enableNetConnect should throw if dispatch not matched for headers and the origin was not allowed by net connect', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.fail('should not be called') + t.assert.fail('should not be called') res.end('should not be called') }) after(() => server.close()) @@ -2547,22 +2428,20 @@ test('MockAgent - enableNetConnect should throw if dispatch not matched for head mockAgent.enableNetConnect('example.com:9999') - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: { 'User-Agent': 'wrong' } }), new MockNotMatchedError(`Mock dispatch not matched for headers '{"User-Agent":"wrong"}' on path '/foo': subsequent request to origin ${baseUrl} was not allowed (net.connect is not enabled for this origin)`)) - - await t.completed }) test('MockAgent - disableNetConnect should throw if dispatch not found by net connect', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.strictEqual(req.url, '/foo') - t.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.url, '/foo') + t.assert.strictEqual(req.method, 'GET') res.setHeader('content-type', 'text/plain') res.end('hello') }) @@ -2584,18 +2463,16 @@ test('MockAgent - disableNetConnect should throw if dispatch not found by net co mockAgent.disableNetConnect() - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET' }), new MockNotMatchedError(`Mock dispatch not matched for path '/foo': subsequent request to origin ${baseUrl} was not allowed (net.connect disabled)`)) - - await t.completed }) test('MockAgent - headers function interceptor', async (t) => { - t = tspl(t, { plan: 8 }) + t.plan(8) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.fail('should not be called') + t.assert.fail('should not be called') res.end('should not be called') }) after(() => server.close()) @@ -2616,19 +2493,19 @@ test('MockAgent - headers function interceptor', async (t) => { path: '/foo', method: 'GET', headers (headers) { - t.strictEqual(typeof headers, 'object') + t.assert.strictEqual(typeof headers, 'object') return !Object.keys(headers).includes('authorization') } }).reply(200, 'foo').times(3) - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: { Authorization: 'Bearer foo' } }), new MockNotMatchedError(`Mock dispatch not matched for headers '{"Authorization":"Bearer foo"}' on path '/foo': subsequent request to origin ${baseUrl} was not allowed (net.connect disabled)`)) - await t.rejects(request(`${baseUrl}/foo`, { + await t.assert.rejects(request(`${baseUrl}/foo`, { method: 'GET', headers: ['Authorization', 'Bearer foo'] }), new MockNotMatchedError(`Mock dispatch not matched for headers '["Authorization","Bearer foo"]' on path '/foo': subsequent request to origin ${baseUrl} was not allowed (net.connect disabled)`)) @@ -2640,25 +2517,23 @@ test('MockAgent - headers function interceptor', async (t) => { foo: 'bar' } }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) } { const { statusCode } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) } - - await t.completed }) test('MockAgent - clients are not garbage collected', async (t) => { const samples = 250 - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - t.fail('should not be called') + t.assert.fail('should not be called') res.end('should not be called') }) after(() => server.close()) @@ -2702,15 +2577,13 @@ test('MockAgent - clients are not garbage collected', async (t) => { results.add(statusCode) } - t.strictEqual(results.size, 1) - t.ok(results.has(200)) - - await t.completed + t.assert.strictEqual(results.size, 1) + t.assert.ok(results.has(200)) }) // https://github.com/nodejs/undici/issues/1321 test('MockAgent - using fetch yields correct statusText', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const mockAgent = new MockAgent() mockAgent.disableNetConnect() @@ -2726,8 +2599,8 @@ test('MockAgent - using fetch yields correct statusText', async (t) => { const { status, statusText } = await fetch('http://localhost:3000/statusText') - t.strictEqual(status, 200) - t.strictEqual(statusText, 'OK') + t.assert.strictEqual(status, 200) + t.assert.strictEqual(statusText, 'OK') mockPool.intercept({ path: '/unknownStatusText', @@ -2735,15 +2608,13 @@ test('MockAgent - using fetch yields correct statusText', async (t) => { }).reply(420, 'Everyday') const unknownStatusCodeRes = await fetch('http://localhost:3000/unknownStatusText') - t.strictEqual(unknownStatusCodeRes.status, 420) - t.strictEqual(unknownStatusCodeRes.statusText, 'unknown') - - await t.completed + t.assert.strictEqual(unknownStatusCodeRes.status, 420) + t.assert.strictEqual(unknownStatusCodeRes.statusText, 'unknown') }) // https://github.com/nodejs/undici/issues/1556 test('MockAgent - using fetch yields a headers object in the reply callback', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() mockAgent.disableNetConnect() @@ -2755,7 +2626,7 @@ test('MockAgent - using fetch yields a headers object in the reply callback', as path: '/headers', method: 'GET' }).reply(200, (opts) => { - t.deepStrictEqual(opts.headers, { + t.assert.deepStrictEqual(opts.headers, { accept: '*/*', 'accept-language': '*', 'sec-fetch-mode': 'cors', @@ -2769,13 +2640,11 @@ test('MockAgent - using fetch yields a headers object in the reply callback', as await fetch('http://localhost:3000/headers', { dispatcher: mockAgent }) - - await t.completed }) // https://github.com/nodejs/undici/issues/1579 test('MockAgent - headers in mock dispatcher intercept should be case-insensitive', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() mockAgent.disableNetConnect() @@ -2801,14 +2670,12 @@ test('MockAgent - headers in mock dispatcher intercept should be case-insensitiv } }) - t.ok(true, 'end') - - await t.completed + t.assert.ok(true, 'end') }) // https://github.com/nodejs/undici/issues/1757 test('MockAgent - reply callback can be asynchronous', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) class MiniflareDispatcher extends Dispatcher { constructor (inner, options) { @@ -2858,7 +2725,7 @@ test('MockAgent - reply callback can be asynchronous', async (t) => { body: JSON.stringify({ foo: 'bar' }) }) - t.deepStrictEqual(await response.json(), { foo: 'bar' }) + t.assert.deepStrictEqual(await response.json(), { foo: 'bar' }) } { @@ -2877,14 +2744,12 @@ test('MockAgent - reply callback can be asynchronous', async (t) => { duplex: 'half' }) - t.deepStrictEqual(await response.json(), { foo: 'bar' }) + t.assert.deepStrictEqual(await response.json(), { foo: 'bar' }) } - - await t.completed }) test('MockAgent - headers should be array of strings', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() mockAgent.disableNetConnect() @@ -2909,18 +2774,16 @@ test('MockAgent - headers should be array of strings', async (t) => { method: 'GET' }) - t.deepStrictEqual(headers['set-cookie'], [ + t.assert.deepStrictEqual(headers['set-cookie'], [ 'foo=bar', 'bar=baz', 'baz=qux' ]) - - await t.completed }) // https://github.com/nodejs/undici/issues/2418 test('MockAgent - Sending ReadableStream body', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() setGlobalDispatcher(mockAgent) @@ -2948,14 +2811,12 @@ test('MockAgent - Sending ReadableStream body', async (t) => { duplex: 'half' }) - t.deepStrictEqual(await response.text(), 'test') - - await t.completed + t.assert.deepStrictEqual(await response.text(), 'test') }) // https://github.com/nodejs/undici/issues/2616 test('MockAgent - headers should be array of strings (fetch)', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() mockAgent.disableNetConnect() @@ -2980,9 +2841,7 @@ test('MockAgent - headers should be array of strings (fetch)', async (t) => { method: 'GET' }) - t.deepStrictEqual(response.headers.getSetCookie(), ['foo=bar', 'bar=baz', 'baz=qux']) - - await t.completed + t.assert.deepStrictEqual(response.headers.getSetCookie(), ['foo=bar', 'bar=baz', 'baz=qux']) }) // https://github.com/nodejs/undici/issues/4146 @@ -2992,13 +2851,12 @@ test('MockAgent - headers should be array of strings (fetch)', async (t) => { '/foo?array=item1,item2' ].forEach(path => { test(`MockAgent - should accept non-standard multi value search parameters when acceptNonStandardSearchParameters is true "${path}"`, async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') - t.end() + t.assert.fail('should not be called') }) after(() => server.close()) @@ -3026,21 +2884,19 @@ test('MockAgent - headers should be array of strings (fetch)', async (t) => { path, method: 'GET' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') - t.deepStrictEqual(trailers, { 'content-md5': 'test' }) + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') + t.assert.deepStrictEqual(trailers, { 'content-md5': 'test' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) - - await t.completed }) }) test('MockAgent - should not accept non-standard search parameters when acceptNonStandardSearchParameters is false (default)', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') @@ -3073,10 +2929,8 @@ test('MockAgent - should not accept non-standard search parameters when acceptNo path: '/foo?array[]=item1&array[]=item2', method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const textResponse = await getResponse(body) - t.strictEqual(textResponse, '(non-intercepted) response from server') - - await t.completed + t.assert.strictEqual(textResponse, '(non-intercepted) response from server') }) diff --git a/test/mock-call-history-log.js b/test/mock-call-history-log.js index 5a7c9de8c0a..493d44a49f0 100644 --- a/test/mock-call-history-log.js +++ b/test/mock-call-history-log.js @@ -1,26 +1,25 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, describe } = require('node:test') const { MockCallHistoryLog } = require('../lib/mock/mock-call-history') const { InvalidArgumentError } = require('../lib/core/errors') describe('MockCallHistoryLog - constructor', () => { function assertConsistent (t, mockCallHistoryLog) { - t.strictEqual(mockCallHistoryLog.body, null) - t.strictEqual(mockCallHistoryLog.headers, undefined) - t.deepStrictEqual(mockCallHistoryLog.searchParams, { query: 'value' }) - t.strictEqual(mockCallHistoryLog.method, 'PUT') - t.strictEqual(mockCallHistoryLog.origin, 'https://localhost:4000') - t.strictEqual(mockCallHistoryLog.path, '/endpoint') - t.strictEqual(mockCallHistoryLog.hash, '#here') - t.strictEqual(mockCallHistoryLog.protocol, 'https:') - t.strictEqual(mockCallHistoryLog.host, 'localhost:4000') - t.strictEqual(mockCallHistoryLog.port, '4000') + t.assert.strictEqual(mockCallHistoryLog.body, null) + t.assert.strictEqual(mockCallHistoryLog.headers, undefined) + t.assert.deepStrictEqual(mockCallHistoryLog.searchParams, { query: 'value' }) + t.assert.strictEqual(mockCallHistoryLog.method, 'PUT') + t.assert.strictEqual(mockCallHistoryLog.origin, 'https://localhost:4000') + t.assert.strictEqual(mockCallHistoryLog.path, '/endpoint') + t.assert.strictEqual(mockCallHistoryLog.hash, '#here') + t.assert.strictEqual(mockCallHistoryLog.protocol, 'https:') + t.assert.strictEqual(mockCallHistoryLog.host, 'localhost:4000') + t.assert.strictEqual(mockCallHistoryLog.port, '4000') } test('should populate class properties with query in path', t => { - t = tspl(t, { plan: 10 }) + t.plan(10) const mockCallHistoryLog = new MockCallHistoryLog({ body: null, @@ -34,7 +33,7 @@ describe('MockCallHistoryLog - constructor', () => { }) test('should populate class properties with query in argument', t => { - t = tspl(t, { plan: 10 }) + t.plan(10) const mockCallHistoryLog = new MockCallHistoryLog({ body: null, @@ -49,15 +48,15 @@ describe('MockCallHistoryLog - constructor', () => { }) test('should throw when url computing failed', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) - t.throws(() => new MockCallHistoryLog({}), new InvalidArgumentError('An error occurred when computing MockCallHistoryLog.url')) + t.assert.throws(() => new MockCallHistoryLog({}), new InvalidArgumentError('An error occurred when computing MockCallHistoryLog.url')) }) }) describe('MockCallHistoryLog - toMap', () => { test('should return a Map of eleven element', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryLog = new MockCallHistoryLog({ body: '"{}"', @@ -67,13 +66,13 @@ describe('MockCallHistoryLog - toMap', () => { path: '/endpoint?query=value#here' }) - t.strictEqual(mockCallHistoryLog.toMap().size, 11) + t.assert.strictEqual(mockCallHistoryLog.toMap().size, 11) }) }) describe('MockCallHistoryLog - toString', () => { test('should return a string with all property', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryLog = new MockCallHistoryLog({ body: '"{ "data": "hello" }"', @@ -83,11 +82,11 @@ describe('MockCallHistoryLog - toString', () => { path: '/endpoint?query=value#here' }) - t.strictEqual(mockCallHistoryLog.toString(), 'protocol->https:|host->localhost:4000|port->4000|origin->https://localhost:4000|path->/endpoint|hash->#here|searchParams->{"query":"value"}|fullUrl->https://localhost:4000/endpoint?query=value#here|method->PUT|body->"{ "data": "hello" }"|headers->{"content-type":"application/json"}') + t.assert.strictEqual(mockCallHistoryLog.toString(), 'protocol->https:|host->localhost:4000|port->4000|origin->https://localhost:4000|path->/endpoint|hash->#here|searchParams->{"query":"value"}|fullUrl->https://localhost:4000/endpoint?query=value#here|method->PUT|body->"{ "data": "hello" }"|headers->{"content-type":"application/json"}') }) test('should return a string when headers is an Array of string Array', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryLog = new MockCallHistoryLog({ body: '"{ "data": "hello" }"', @@ -97,6 +96,6 @@ describe('MockCallHistoryLog - toString', () => { path: '/endpoint?query=value#here' }) - t.strictEqual(mockCallHistoryLog.toString(), 'protocol->https:|host->localhost:4000|port->4000|origin->https://localhost:4000|path->/endpoint|hash->#here|searchParams->{"query":"value"}|fullUrl->https://localhost:4000/endpoint?query=value#here|method->PUT|body->"{ "data": "hello" }"|headers->["content-type",["application/json","application/xml"]]') + t.assert.strictEqual(mockCallHistoryLog.toString(), 'protocol->https:|host->localhost:4000|port->4000|origin->https://localhost:4000|path->/endpoint|hash->#here|searchParams->{"query":"value"}|fullUrl->https://localhost:4000/endpoint?query=value#here|method->PUT|body->"{ "data": "hello" }"|headers->["content-type",["application/json","application/xml"]]') }) }) diff --git a/test/mock-call-history.js b/test/mock-call-history.js index 2c4d9bbeb43..6e05f21f9fa 100644 --- a/test/mock-call-history.js +++ b/test/mock-call-history.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, describe } = require('node:test') const { MockCallHistory, MockCallHistoryLog } = require('../lib/mock/mock-call-history') const { kMockCallHistoryAddLog } = require('../lib/mock/mock-symbols') @@ -8,148 +7,148 @@ const { InvalidArgumentError } = require('../lib/core/errors') describe('MockCallHistory - constructor', () => { test('should returns a MockCallHistory', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistory = new MockCallHistory() - t.ok(mockCallHistory instanceof MockCallHistory) + t.assert.ok(mockCallHistory instanceof MockCallHistory) }) }) describe('MockCallHistory - add log', () => { test('should add a log', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockCallHistoryHello = new MockCallHistory() - t.strictEqual(mockCallHistoryHello.calls().length, 0) + t.assert.strictEqual(mockCallHistoryHello.calls().length, 0) mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/', origin: 'https://localhost:4000' }) - t.strictEqual(mockCallHistoryHello.calls().length, 1) + t.assert.strictEqual(mockCallHistoryHello.calls().length, 1) }) }) describe('MockCallHistory - calls', () => { test('should returns every logs', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/', origin: 'https://localhost:4000' }) mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/', origin: 'https://localhost:4000' }) - t.strictEqual(mockCallHistoryHello.calls().length, 2) + t.assert.strictEqual(mockCallHistoryHello.calls().length, 2) }) test('should returns empty array when no logs', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') - t.ok(mockCallHistoryHello.calls() instanceof Array) + t.assert.ok(mockCallHistoryHello.calls() instanceof Array) }) }) describe('MockCallHistory - firstCall', () => { test('should returns the first log registered', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/', origin: 'http://localhost:4000' }) mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/noop', origin: 'http://localhost:4000' }) - t.strictEqual(mockCallHistoryHello.firstCall()?.path, '/') + t.assert.strictEqual(mockCallHistoryHello.firstCall()?.path, '/') }) test('should returns undefined when no logs', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') - t.strictEqual(mockCallHistoryHello.firstCall(), undefined) + t.assert.strictEqual(mockCallHistoryHello.firstCall(), undefined) }) }) describe('MockCallHistory - lastCall', () => { test('should returns the first log registered', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/', origin: 'http://localhost:4000' }) mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/noop', origin: 'http://localhost:4000' }) - t.strictEqual(mockCallHistoryHello.lastCall()?.path, '/noop') + t.assert.strictEqual(mockCallHistoryHello.lastCall()?.path, '/noop') }) test('should returns undefined when no logs', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') - t.strictEqual(mockCallHistoryHello.lastCall(), undefined) + t.assert.strictEqual(mockCallHistoryHello.lastCall(), undefined) }) }) describe('MockCallHistory - nthCall', () => { test('should returns the nth log registered', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockCallHistoryHello = new MockCallHistory('hello') mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/', origin: 'http://localhost:4000' }) mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/noop', origin: 'http://localhost:4000' }) - t.strictEqual(mockCallHistoryHello.nthCall(1)?.path, '/') - t.strictEqual(mockCallHistoryHello.nthCall(2)?.path, '/noop') + t.assert.strictEqual(mockCallHistoryHello.nthCall(1)?.path, '/') + t.assert.strictEqual(mockCallHistoryHello.nthCall(2)?.path, '/noop') }) test('should returns undefined when no logs', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') - t.strictEqual(mockCallHistoryHello.nthCall(3), undefined) + t.assert.strictEqual(mockCallHistoryHello.nthCall(3), undefined) }) test('should throw if index is not a number', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') - t.throws(() => mockCallHistoryHello.nthCall('noop'), new InvalidArgumentError('nthCall must be called with a number')) + t.assert.throws(() => mockCallHistoryHello.nthCall('noop'), new InvalidArgumentError('nthCall must be called with a number')) }) test('should throw if index is not an integer', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') - t.throws(() => mockCallHistoryHello.nthCall(1.3), new InvalidArgumentError('nthCall must be called with an integer')) + t.assert.throws(() => mockCallHistoryHello.nthCall(1.3), new InvalidArgumentError('nthCall must be called with an integer')) }) test('should throw if index is equal to zero', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') - t.throws(() => mockCallHistoryHello.nthCall(0), new InvalidArgumentError('nthCall must be called with a positive value. use firstCall or lastCall instead')) + t.assert.throws(() => mockCallHistoryHello.nthCall(0), new InvalidArgumentError('nthCall must be called with a positive value. use firstCall or lastCall instead')) }) test('should throw if index is negative', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') - t.throws(() => mockCallHistoryHello.nthCall(-1), new InvalidArgumentError('nthCall must be called with a positive value. use firstCall or lastCall instead')) + t.assert.throws(() => mockCallHistoryHello.nthCall(-1), new InvalidArgumentError('nthCall must be called with a positive value. use firstCall or lastCall instead')) }) }) describe('MockCallHistory - iterator', () => { test('should permit to iterate over logs with for..of', t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const mockCallHistoryHello = new MockCallHistory('hello') @@ -157,13 +156,13 @@ describe('MockCallHistory - iterator', () => { mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/noop', origin: 'http://localhost:4000' }) for (const log of mockCallHistoryHello) { - t.ok(log instanceof MockCallHistoryLog) - t.ok(typeof log.path === 'string') + t.assert.ok(log instanceof MockCallHistoryLog) + t.assert.ok(typeof log.path === 'string') } }) test('should permit to iterate over logs with spread operator', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockCallHistoryHello = new MockCallHistory('hello') @@ -172,14 +171,14 @@ describe('MockCallHistory - iterator', () => { const logs = [...mockCallHistoryHello] - t.ok(logs.every((log) => log instanceof MockCallHistoryLog)) - t.strictEqual(logs.length, 2) + t.assert.ok(logs.every((log) => log instanceof MockCallHistoryLog)) + t.assert.strictEqual(logs.length, 2) }) }) describe('MockCallHistory - filterCalls without options', () => { test('should filter logs with a function', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockCallHistoryHello = new MockCallHistory('hello') @@ -188,12 +187,12 @@ describe('MockCallHistory - filterCalls without options', () => { const filtered = mockCallHistoryHello.filterCalls((log) => log.path === '/noop') - t.strictEqual(filtered?.[0]?.path, '/noop') - t.strictEqual(filtered.length, 1) + t.assert.strictEqual(filtered?.[0]?.path, '/noop') + t.assert.strictEqual(filtered.length, 1) }) test('should filter logs with a regexp', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockCallHistoryHello = new MockCallHistory('hello') @@ -202,12 +201,12 @@ describe('MockCallHistory - filterCalls without options', () => { const filtered = mockCallHistoryHello.filterCalls(/https:\/\//) - t.strictEqual(filtered?.[0]?.path, '/noop') - t.strictEqual(filtered.length, 1) + t.assert.strictEqual(filtered?.[0]?.path, '/noop') + t.assert.strictEqual(filtered.length, 1) }) test('should filter logs with an object', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockCallHistoryHello = new MockCallHistory('hello') @@ -217,12 +216,12 @@ describe('MockCallHistory - filterCalls without options', () => { const filtered = mockCallHistoryHello.filterCalls({ protocol: 'https:' }) - t.strictEqual(filtered?.[0]?.path, '/noop') - t.strictEqual(filtered.length, 1) + t.assert.strictEqual(filtered?.[0]?.path, '/noop') + t.assert.strictEqual(filtered.length, 1) }) test('should returns every logs with an empty object', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') @@ -232,11 +231,11 @@ describe('MockCallHistory - filterCalls without options', () => { const filtered = mockCallHistoryHello.filterCalls({}) - t.strictEqual(filtered.length, 3) + t.assert.strictEqual(filtered.length, 3) }) test('should filter logs with an object with host property', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') @@ -246,11 +245,11 @@ describe('MockCallHistory - filterCalls without options', () => { const filtered = mockCallHistoryHello.filterCalls({ host: /localhost/ }) - t.strictEqual(filtered.length, 2) + t.assert.strictEqual(filtered.length, 2) }) test('should filter logs with an object with port property', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') @@ -260,11 +259,11 @@ describe('MockCallHistory - filterCalls without options', () => { const filtered = mockCallHistoryHello.filterCalls({ port: '1000' }) - t.strictEqual(filtered.length, 1) + t.assert.strictEqual(filtered.length, 1) }) test('should filter logs with an object with hash property', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') @@ -274,11 +273,11 @@ describe('MockCallHistory - filterCalls without options', () => { const filtered = mockCallHistoryHello.filterCalls({ hash: '#hello' }) - t.strictEqual(filtered.length, 1) + t.assert.strictEqual(filtered.length, 1) }) test('should filter logs with an object with fullUrl property', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') @@ -288,11 +287,11 @@ describe('MockCallHistory - filterCalls without options', () => { const filtered = mockCallHistoryHello.filterCalls({ fullUrl: 'http://localhost:1000/#hello' }) - t.strictEqual(filtered.length, 1) + t.assert.strictEqual(filtered.length, 1) }) test('should filter logs with an object with method property', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') @@ -302,11 +301,11 @@ describe('MockCallHistory - filterCalls without options', () => { const filtered = mockCallHistoryHello.filterCalls({ method: /(PUT|GET)/ }) - t.strictEqual(filtered.length, 2) + t.assert.strictEqual(filtered.length, 2) }) test('should use "OR" operator', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') @@ -316,11 +315,11 @@ describe('MockCallHistory - filterCalls without options', () => { const filtered = mockCallHistoryHello.filterCalls({ protocol: 'https:', path: /^\/$/ }) - t.strictEqual(filtered.length, 2) + t.assert.strictEqual(filtered.length, 2) }) test('should returns no duplicated logs', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') @@ -330,63 +329,63 @@ describe('MockCallHistory - filterCalls without options', () => { const filtered = mockCallHistoryHello.filterCalls({ protocol: 'https:', origin: /localhost/ }) - t.strictEqual(filtered.length, 3) + t.assert.strictEqual(filtered.length, 3) }) test('should throw if criteria is typeof number', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/', origin: 'http://localhost:4000' }) - t.throws(() => mockCallHistoryHello.filterCalls({ path: 3 }), new InvalidArgumentError('path parameter should be one of string, regexp, undefined or null')) + t.assert.throws(() => mockCallHistoryHello.filterCalls({ path: 3 }), new InvalidArgumentError('path parameter should be one of string, regexp, undefined or null')) }) test('should throw if criteria is not a function, regexp, nor object', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/', origin: 'http://localhost:4000' }) - t.throws(() => mockCallHistoryHello.filterCalls(3), new InvalidArgumentError('criteria parameter should be one of function, regexp, or object')) + t.assert.throws(() => mockCallHistoryHello.filterCalls(3), new InvalidArgumentError('criteria parameter should be one of function, regexp, or object')) }) }) describe('MockCallHistory - filterCalls with options', () => { test('should throw if options.operator is not a valid string', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/', origin: 'http://localhost:4000' }) - t.throws(() => mockCallHistoryHello.filterCalls({ path: '/' }, { operator: 'wrong' }), new InvalidArgumentError('options.operator must to be a case insensitive string equal to \'OR\' or \'AND\'')) + t.assert.throws(() => mockCallHistoryHello.filterCalls({ path: '/' }, { operator: 'wrong' }), new InvalidArgumentError('options.operator must to be a case insensitive string equal to \'OR\' or \'AND\'')) }) test('should not throw if options.operator is "or"', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/', origin: 'http://localhost:4000' }) - t.doesNotThrow(() => mockCallHistoryHello.filterCalls({ path: '/' }, { operator: 'or' })) + t.assert.doesNotThrow(() => mockCallHistoryHello.filterCalls({ path: '/' }, { operator: 'or' })) }) test('should not throw if options.operator is "and"', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') mockCallHistoryHello[kMockCallHistoryAddLog]({ path: '/', origin: 'http://localhost:4000' }) - t.doesNotThrow(() => mockCallHistoryHello.filterCalls({ path: '/' }, { operator: 'and' })) + t.assert.doesNotThrow(() => mockCallHistoryHello.filterCalls({ path: '/' }, { operator: 'and' })) }) test('should use "OR" operator if options is an empty object', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') @@ -395,11 +394,11 @@ describe('MockCallHistory - filterCalls with options', () => { const filtered = mockCallHistoryHello.filterCalls({ path: '/' }, {}) - t.strictEqual(filtered.length, 1) + t.assert.strictEqual(filtered.length, 1) }) test('should use "AND" operator correctly', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') @@ -410,11 +409,11 @@ describe('MockCallHistory - filterCalls with options', () => { const filtered = mockCallHistoryHello.filterCalls({ path: '/', port: '4000' }, { operator: 'AND' }) - t.strictEqual(filtered.length, 2) + t.assert.strictEqual(filtered.length, 2) }) test('should use "AND" operator with a lot of filters', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockCallHistoryHello = new MockCallHistory('hello') @@ -426,6 +425,6 @@ describe('MockCallHistory - filterCalls with options', () => { const filtered = mockCallHistoryHello.filterCalls({ path: '/', port: '1000', host: /localhost/, method: /(POST|PUT)/ }, { operator: 'AND' }) - t.strictEqual(filtered.length, 2) + t.assert.strictEqual(filtered.length, 2) }) }) diff --git a/test/mock-client.js b/test/mock-client.js index 313c628374c..6cdd3df10f4 100644 --- a/test/mock-client.js +++ b/test/mock-client.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, after, describe } = require('node:test') const { createServer } = require('node:http') const { promisify } = require('node:util') @@ -14,26 +13,26 @@ const Dispatcher = require('../lib/dispatcher/dispatcher') describe('MockClient - constructor', () => { test('fails if opts.agent does not implement `get` method', t => { - t = tspl(t, { plan: 1 }) - t.throws(() => new MockClient('http://localhost:9999', { agent: { get: 'not a function' } }), InvalidArgumentError) + t.plan(1) + t.assert.throws(() => new MockClient('http://localhost:9999', { agent: { get: 'not a function' } }), InvalidArgumentError) }) test('sets agent', t => { - t = tspl(t, { plan: 1 }) - t.doesNotThrow(() => new MockClient('http://localhost:9999', { agent: new MockAgent({ connections: 1 }) })) + t.plan(1) + t.assert.doesNotThrow(() => new MockClient('http://localhost:9999', { agent: new MockAgent({ connections: 1 }) })) }) test('should implement the Dispatcher API', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockClient = new MockClient('http://localhost:9999', { agent: new MockAgent({ connections: 1 }) }) - t.ok(mockClient instanceof Dispatcher) + t.assert.ok(mockClient instanceof Dispatcher) }) }) describe('MockClient - dispatch', () => { test('should handle a single interceptor', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -57,7 +56,7 @@ describe('MockClient - dispatch', () => { } ] - t.doesNotThrow(() => mockClient.dispatch({ + t.assert.doesNotThrow(() => mockClient.dispatch({ path: '/foo', method: 'GET' }, { @@ -68,7 +67,7 @@ describe('MockClient - dispatch', () => { }) test('should directly throw error from mockDispatch function if error is not a MockNotMatchedError', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -92,7 +91,7 @@ describe('MockClient - dispatch', () => { } ] - t.throws(() => mockClient.dispatch({ + t.assert.throws(() => mockClient.dispatch({ path: '/foo', method: 'GET' }, { @@ -104,7 +103,7 @@ describe('MockClient - dispatch', () => { }) test('MockClient - intercept should return a MockInterceptor', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -118,41 +117,41 @@ test('MockClient - intercept should return a MockInterceptor', (t) => { method: 'GET' }) - t.ok(interceptor instanceof MockInterceptor) + t.assert.ok(interceptor instanceof MockInterceptor) }) describe('MockClient - intercept validation', () => { test('it should error if no options specified in the intercept', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent({ connections: 1 }) after(() => mockAgent.close()) const mockClient = mockAgent.get('http://localhost:9999') - t.throws(() => mockClient.intercept(), new InvalidArgumentError('opts must be an object')) + t.assert.throws(() => mockClient.intercept(), new InvalidArgumentError('opts must be an object')) }) test('it should error if no path specified in the intercept', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent({ connections: 1 }) after(() => mockAgent.close()) const mockClient = mockAgent.get('http://localhost:9999') - t.throws(() => mockClient.intercept({}), new InvalidArgumentError('opts.path must be defined')) + t.assert.throws(() => mockClient.intercept({}), new InvalidArgumentError('opts.path must be defined')) }) test('it should default to GET if no method specified in the intercept', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent({ connections: 1 }) after(() => mockAgent.close()) const mockClient = mockAgent.get('http://localhost:9999') - t.doesNotThrow(() => mockClient.intercept({ path: '/foo' })) + t.assert.doesNotThrow(() => mockClient.intercept({ path: '/foo' })) }) test('it should uppercase the method - https://github.com/nodejs/undici/issues/1320', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() const mockClient = mockAgent.get('http://localhost:3000') @@ -164,12 +163,12 @@ describe('MockClient - intercept validation', () => { method: 'patch' }).reply(200, 'Hello!') - t.strictEqual(mockClient[kDispatches][0].method, 'PATCH') + t.assert.strictEqual(mockClient[kDispatches][0].method, 'PATCH') }) }) test('MockClient - close should run without error', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -192,17 +191,16 @@ test('MockClient - close should run without error', async (t) => { ] await mockClient.close() - t.ok(true, 'pass') + t.assert.ok(true, 'pass') }) test('MockClient - should be able to set as globalDispatcher', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') - t.end() + t.assert.fail('should not be called') }) after(() => server.close()) @@ -214,7 +212,7 @@ test('MockClient - should be able to set as globalDispatcher', async (t) => { after(() => mockAgent.close()) const mockClient = mockAgent.get(baseUrl) - t.ok(mockClient instanceof MockClient) + t.assert.ok(mockClient instanceof MockClient) setGlobalDispatcher(mockClient) mockClient.intercept({ @@ -225,20 +223,19 @@ test('MockClient - should be able to set as globalDispatcher', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.deepStrictEqual(response, 'hello') + t.assert.deepStrictEqual(response, 'hello') }) test('MockClient - should support query params', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') - t.end() + t.assert.fail('should not be called') }) after(() => server.close()) @@ -250,7 +247,7 @@ test('MockClient - should support query params', async (t) => { after(() => mockAgent.close()) const mockClient = mockAgent.get(baseUrl) - t.ok(mockClient instanceof MockClient) + t.assert.ok(mockClient instanceof MockClient) setGlobalDispatcher(mockClient) const query = { @@ -266,20 +263,19 @@ test('MockClient - should support query params', async (t) => { method: 'GET', query }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.deepStrictEqual(response, 'hello') + t.assert.deepStrictEqual(response, 'hello') }) test('MockClient - should intercept query params with hardcoded path', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') - t.end() + t.assert.fail('should not be called') }) after(() => server.close()) @@ -291,7 +287,7 @@ test('MockClient - should intercept query params with hardcoded path', async (t) after(() => mockAgent.close()) const mockClient = mockAgent.get(baseUrl) - t.ok(mockClient instanceof MockClient) + t.assert.ok(mockClient instanceof MockClient) setGlobalDispatcher(mockClient) const query = { @@ -306,20 +302,19 @@ test('MockClient - should intercept query params with hardcoded path', async (t) method: 'GET', query }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.deepStrictEqual(response, 'hello') + t.assert.deepStrictEqual(response, 'hello') }) test('MockClient - should intercept query params regardless of key ordering', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') - t.end() + t.assert.fail('should not be called') }) after(() => server.close()) @@ -331,7 +326,7 @@ test('MockClient - should intercept query params regardless of key ordering', as after(() => mockAgent.close()) const mockClient = mockAgent.get(baseUrl) - t.ok(mockClient instanceof MockClient) + t.assert.ok(mockClient instanceof MockClient) setGlobalDispatcher(mockClient) const query = { @@ -354,20 +349,19 @@ test('MockClient - should intercept query params regardless of key ordering', as method: 'GET', query }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.deepStrictEqual(response, 'hello') + t.assert.deepStrictEqual(response, 'hello') }) test('MockClient - should be able to use as a local dispatcher', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') - t.end() + t.assert.fail('should not be called') }) after(() => server.close()) @@ -379,7 +373,7 @@ test('MockClient - should be able to use as a local dispatcher', async (t) => { after(() => mockAgent.close()) const mockClient = mockAgent.get(baseUrl) - t.ok(mockClient instanceof MockClient) + t.assert.ok(mockClient instanceof MockClient) mockClient.intercept({ path: '/foo', @@ -390,20 +384,19 @@ test('MockClient - should be able to use as a local dispatcher', async (t) => { method: 'GET', dispatcher: mockClient }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.deepStrictEqual(response, 'hello') + t.assert.deepStrictEqual(response, 'hello') }) test('MockClient - basic intercept with MockClient.request', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') - t.end() + t.assert.fail('should not be called') }) after(() => server.close()) @@ -414,7 +407,7 @@ test('MockClient - basic intercept with MockClient.request', async (t) => { const mockAgent = new MockAgent({ connections: 1 }) after(() => mockAgent.close()) const mockClient = mockAgent.get(baseUrl) - t.ok(mockClient instanceof MockClient) + t.assert.ok(mockClient instanceof MockClient) mockClient.intercept({ path: '/foo?hello=there&see=ya', @@ -431,18 +424,18 @@ test('MockClient - basic intercept with MockClient.request', async (t) => { method: 'POST', body: 'form1=data1&form2=data2' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') - t.deepStrictEqual(trailers, { 'content-md5': 'test' }) + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') + t.assert.deepStrictEqual(trailers, { 'content-md5': 'test' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) }) test('MockClient - cleans mocks', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') @@ -458,25 +451,25 @@ test('MockClient - cleans mocks', async (t) => { after(() => mockAgent.close()) const mockClient = mockAgent.get(baseUrl) - t.ok(mockClient instanceof MockClient) + t.assert.ok(mockClient instanceof MockClient) setGlobalDispatcher(mockClient) mockClient.intercept({ path: '/foo', method: 'GET' }).reply(500, () => { - t.fail('should not be called') + t.assert.fail('should not be called') }) mockClient.cleanMocks() - t.strictEqual(mockClient[kDispatches].length, 0) + t.assert.strictEqual(mockClient[kDispatches].length, 0) const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.deepStrictEqual(response, 'hello') + t.assert.deepStrictEqual(response, 'hello') }) diff --git a/test/mock-errors.js b/test/mock-errors.js index 58ec2b52b9f..7ca1b8dc562 100644 --- a/test/mock-errors.js +++ b/test/mock-errors.js @@ -1,27 +1,26 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { describe, test } = require('node:test') const { mockErrors, errors } = require('..') describe('MockNotMatchedError', () => { test('should implement an UndiciError', t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const mockError = new mockErrors.MockNotMatchedError() - t.ok(mockError instanceof errors.UndiciError) - t.deepStrictEqual(mockError.name, 'MockNotMatchedError') - t.deepStrictEqual(mockError.code, 'UND_MOCK_ERR_MOCK_NOT_MATCHED') - t.deepStrictEqual(mockError.message, 'The request does not match any registered mock dispatches') + t.assert.ok(mockError instanceof errors.UndiciError) + t.assert.deepStrictEqual(mockError.name, 'MockNotMatchedError') + t.assert.deepStrictEqual(mockError.code, 'UND_MOCK_ERR_MOCK_NOT_MATCHED') + t.assert.deepStrictEqual(mockError.message, 'The request does not match any registered mock dispatches') }) test('should set a custom message', t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const mockError = new mockErrors.MockNotMatchedError('custom message') - t.ok(mockError instanceof errors.UndiciError) - t.deepStrictEqual(mockError.name, 'MockNotMatchedError') - t.deepStrictEqual(mockError.code, 'UND_MOCK_ERR_MOCK_NOT_MATCHED') - t.deepStrictEqual(mockError.message, 'custom message') + t.assert.ok(mockError instanceof errors.UndiciError) + t.assert.deepStrictEqual(mockError.name, 'MockNotMatchedError') + t.assert.deepStrictEqual(mockError.code, 'UND_MOCK_ERR_MOCK_NOT_MATCHED') + t.assert.deepStrictEqual(mockError.message, 'custom message') }) }) diff --git a/test/mock-interceptor-unused-assertions.js b/test/mock-interceptor-unused-assertions.js index ddb5aeabab1..ca8a840d8cf 100644 --- a/test/mock-interceptor-unused-assertions.js +++ b/test/mock-interceptor-unused-assertions.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, beforeEach, afterEach } = require('node:test') const { MockAgent, setGlobalDispatcher } = require('..') const PendingInterceptorsFormatter = require('../lib/mock/pending-interceptors-formatter') @@ -46,13 +45,13 @@ function mockAgentWithOneInterceptor () { } test('1 pending interceptor', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) try { mockAgentWithOneInterceptor().assertNoPendingInterceptors({ pendingInterceptorsFormatter }) - t.fail('Should have thrown') + t.assert.fail('Should have thrown') } catch (err) { - t.deepStrictEqual(err.message, tableRowsAlignedToLeft + t.assert.deepStrictEqual(err.message, tableRowsAlignedToLeft ? ` 1 interceptor is pending: @@ -75,7 +74,7 @@ test('1 pending interceptor', t => { }) test('2 pending interceptors', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const withTwoInterceptors = mockAgentWithOneInterceptor() withTwoInterceptors @@ -85,7 +84,7 @@ test('2 pending interceptors', t => { try { withTwoInterceptors.assertNoPendingInterceptors({ pendingInterceptorsFormatter }) } catch (err) { - t.deepStrictEqual(err.message, tableRowsAlignedToLeft + t.assert.deepStrictEqual(err.message, tableRowsAlignedToLeft ? ` 2 interceptors are pending: @@ -110,7 +109,7 @@ test('2 pending interceptors', t => { }) test('Variations of persist(), times(), and pending status', async t => { - t = tspl(t, { plan: 6 }) + t.plan(6) // Agent with unused interceptor const agent = mockAgentWithOneInterceptor() @@ -128,20 +127,20 @@ test('Variations of persist(), times(), and pending status', async t => { .intercept({ method: 'GET', path: '/persistent/used' }) .reply(200, 'OK') .persist() - t.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/persistent/used' })).statusCode, 200) + t.assert.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/persistent/used' })).statusCode, 200) // Consumed without persist() agent.get(origin) .intercept({ method: 'post', path: '/transient/pending' }) .reply(201, 'Created') - t.deepStrictEqual((await agent.request({ origin, method: 'POST', path: '/transient/pending' })).statusCode, 201) + t.assert.deepStrictEqual((await agent.request({ origin, method: 'POST', path: '/transient/pending' })).statusCode, 201) // Partially pending with times() agent.get(origin) .intercept({ method: 'get', path: '/times/partial' }) .reply(200, 'OK') .times(5) - t.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/times/partial' })).statusCode, 200) + t.assert.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/times/partial' })).statusCode, 200) // Unused with times() agent.get(origin) @@ -154,14 +153,14 @@ test('Variations of persist(), times(), and pending status', async t => { .intercept({ method: 'get', path: '/times/pending' }) .reply(200, 'OK') .times(2) - t.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/times/pending' })).statusCode, 200) - t.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/times/pending' })).statusCode, 200) + t.assert.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/times/pending' })).statusCode, 200) + t.assert.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/times/pending' })).statusCode, 200) try { agent.assertNoPendingInterceptors({ pendingInterceptorsFormatter }) - t.fail('Should have thrown') + t.assert.fail('Should have thrown') } catch (err) { - t.deepStrictEqual(err.message, tableRowsAlignedToLeft + t.assert.deepStrictEqual(err.message, tableRowsAlignedToLeft ? ` 4 interceptors are pending: @@ -190,33 +189,33 @@ test('Variations of persist(), times(), and pending status', async t => { }) test('works when no interceptors are registered', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const agent = new MockAgent() agent.disableNetConnect() - t.deepStrictEqual(agent.pendingInterceptors(), []) - t.doesNotThrow(() => agent.assertNoPendingInterceptors()) + t.assert.deepStrictEqual(agent.pendingInterceptors(), []) + t.assert.doesNotThrow(() => agent.assertNoPendingInterceptors()) }) test('works when all interceptors are pending', async t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const agent = new MockAgent() agent.disableNetConnect() agent.get(origin).intercept({ method: 'get', path: '/' }).reply(200, 'OK') - t.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/' })).statusCode, 200) + t.assert.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/' })).statusCode, 200) agent.get(origin).intercept({ method: 'get', path: '/persistent' }).reply(200, 'OK') - t.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/persistent' })).statusCode, 200) + t.assert.deepStrictEqual((await agent.request({ origin, method: 'GET', path: '/persistent' })).statusCode, 200) - t.deepStrictEqual(agent.pendingInterceptors(), []) - t.doesNotThrow(() => agent.assertNoPendingInterceptors()) + t.assert.deepStrictEqual(agent.pendingInterceptors(), []) + t.assert.doesNotThrow(() => agent.assertNoPendingInterceptors()) }) test('defaults to rendering output with terminal color when process.env.CI is unset', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) // This ensures that the test works in an environment where the CI env var is set. const oldCiEnvVar = process.env.CI @@ -224,9 +223,9 @@ test('defaults to rendering output with terminal color when process.env.CI is un try { mockAgentWithOneInterceptor().assertNoPendingInterceptors() - t.fail('Should have thrown') + t.assert.fail('Should have thrown') } catch (err) { - t.deepStrictEqual(err.message, tableRowsAlignedToLeft + t.assert.deepStrictEqual(err.message, tableRowsAlignedToLeft ? ` 1 interceptor is pending: @@ -257,9 +256,9 @@ test('defaults to rendering output with terminal color when process.env.CI is un }) test('returns unused interceptors', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) - t.deepStrictEqual(mockAgentWithOneInterceptor().pendingInterceptors(), [ + t.assert.deepStrictEqual(mockAgentWithOneInterceptor().pendingInterceptors(), [ { timesInvoked: 0, times: 1, diff --git a/test/mock-interceptor.js b/test/mock-interceptor.js index 09b3b13c5a6..1114b9075d3 100644 --- a/test/mock-interceptor.js +++ b/test/mock-interceptor.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { describe, test, after } = require('node:test') const { MockInterceptor, MockScope } = require('../lib/mock/mock-interceptor') const MockAgent = require('../lib/mock/mock-agent') @@ -10,65 +9,65 @@ const { fetch } = require('../lib/web/fetch/index') describe('MockInterceptor - path', () => { test('should remove hash fragment from paths', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockInterceptor = new MockInterceptor({ path: '#foobar', method: '' }, []) - t.strictEqual(mockInterceptor[kDispatchKey].path, '') + t.assert.strictEqual(mockInterceptor[kDispatchKey].path, '') }) }) describe('MockInterceptor - reply', () => { test('should return MockScope', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockInterceptor = new MockInterceptor({ path: '', method: '' }, []) const result = mockInterceptor.reply(200, 'hello') - t.ok(result instanceof MockScope) + t.assert.ok(result instanceof MockScope) }) test('should error if passed options invalid', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockInterceptor = new MockInterceptor({ path: '', method: '' }, []) - t.throws(() => mockInterceptor.reply(), new InvalidArgumentError('statusCode must be defined')) - t.throws(() => mockInterceptor.reply(200, '', 'hello'), new InvalidArgumentError('responseOptions must be an object')) + t.assert.throws(() => mockInterceptor.reply(), new InvalidArgumentError('statusCode must be defined')) + t.assert.throws(() => mockInterceptor.reply(200, '', 'hello'), new InvalidArgumentError('responseOptions must be an object')) }) }) describe('MockInterceptor - reply callback', () => { test('should return MockScope', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockInterceptor = new MockInterceptor({ path: '', method: '' }, []) const result = mockInterceptor.reply(200, () => 'hello') - t.ok(result instanceof MockScope) + t.assert.ok(result instanceof MockScope) }) test('should error if passed options invalid', t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const mockInterceptor = new MockInterceptor({ path: '', method: '' }, []) - t.throws(() => mockInterceptor.reply(), new InvalidArgumentError('statusCode must be defined')) - t.throws(() => mockInterceptor.reply(200, () => { }, 'hello'), new InvalidArgumentError('responseOptions must be an object')) - t.throws(() => mockInterceptor.reply(200, () => { }, null), new InvalidArgumentError('responseOptions must be an object')) + t.assert.throws(() => mockInterceptor.reply(), new InvalidArgumentError('statusCode must be defined')) + t.assert.throws(() => mockInterceptor.reply(200, () => { }, 'hello'), new InvalidArgumentError('responseOptions must be an object')) + t.assert.throws(() => mockInterceptor.reply(200, () => { }, null), new InvalidArgumentError('responseOptions must be an object')) }) }) describe('MockInterceptor - reply options callback', () => { test('should return MockScope', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockInterceptor = new MockInterceptor({ path: '', @@ -78,7 +77,7 @@ describe('MockInterceptor - reply options callback', () => { statusCode: 200, data: 'hello' })) - t.ok(result instanceof MockScope) + t.assert.ok(result instanceof MockScope) // Test parameters @@ -92,7 +91,7 @@ describe('MockInterceptor - reply options callback', () => { path: '/test', method: 'GET' }).reply((options) => { - t.deepStrictEqual(options, { path: '/test', method: 'GET', headers: { foo: 'bar' } }) + t.assert.deepStrictEqual(options, { path: '/test', method: 'GET', headers: { foo: 'bar' } }) return { statusCode: 200, data: 'hello' } }) @@ -108,7 +107,7 @@ describe('MockInterceptor - reply options callback', () => { }) test('should handle undefined data', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const mockInterceptor = new MockInterceptor({ path: '', @@ -118,7 +117,7 @@ describe('MockInterceptor - reply options callback', () => { statusCode: 200, data: undefined })) - t.ok(result instanceof MockScope) + t.assert.ok(result instanceof MockScope) // Test parameters @@ -132,7 +131,7 @@ describe('MockInterceptor - reply options callback', () => { path: '/test', method: 'GET' }).reply((options) => { - t.deepStrictEqual(options, { path: '/test', method: 'GET', headers: { foo: 'bar' } }) + t.assert.deepStrictEqual(options, { path: '/test', method: 'GET', headers: { foo: 'bar' } }) return { statusCode: 200, data: 'hello' } }) @@ -148,7 +147,7 @@ describe('MockInterceptor - reply options callback', () => { }) test('should error if passed options invalid', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const baseUrl = 'http://localhost:9999' const mockAgent = new MockAgent() @@ -183,7 +182,7 @@ describe('MockInterceptor - reply options callback', () => { responseOptions: 42 })) - t.throws(() => mockPool.dispatch({ + t.assert.throws(() => mockPool.dispatch({ path: '/test-return-undefined', method: 'GET' }, { @@ -192,7 +191,7 @@ describe('MockInterceptor - reply options callback', () => { onComplete: () => { } }), new InvalidArgumentError('reply options callback must return an object')) - t.throws(() => mockPool.dispatch({ + t.assert.throws(() => mockPool.dispatch({ path: '/test-return-null', method: 'GET' }, { @@ -201,7 +200,7 @@ describe('MockInterceptor - reply options callback', () => { onComplete: () => { } }), new InvalidArgumentError('reply options callback must return an object')) - t.throws(() => mockPool.dispatch({ + t.assert.throws(() => mockPool.dispatch({ path: '/test3', method: 'GET' }, { @@ -210,7 +209,7 @@ describe('MockInterceptor - reply options callback', () => { onComplete: () => { } }), new InvalidArgumentError('responseOptions must be an object')) - t.throws(() => mockPool.dispatch({ + t.assert.throws(() => mockPool.dispatch({ path: '/test4', method: 'GET' }, { @@ -223,79 +222,79 @@ describe('MockInterceptor - reply options callback', () => { describe('MockInterceptor - replyWithError', () => { test('should return MockScope', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockInterceptor = new MockInterceptor({ path: '', method: '' }, []) const result = mockInterceptor.replyWithError(new Error('kaboom')) - t.ok(result instanceof MockScope) + t.assert.ok(result instanceof MockScope) }) test('should error if passed options invalid', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockInterceptor = new MockInterceptor({ path: '', method: '' }, []) - t.throws(() => mockInterceptor.replyWithError(), new InvalidArgumentError('error must be defined')) + t.assert.throws(() => mockInterceptor.replyWithError(), new InvalidArgumentError('error must be defined')) }) }) describe('MockInterceptor - defaultReplyHeaders', () => { test('should return MockInterceptor', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockInterceptor = new MockInterceptor({ path: '', method: '' }, []) const result = mockInterceptor.defaultReplyHeaders({}) - t.ok(result instanceof MockInterceptor) + t.assert.ok(result instanceof MockInterceptor) }) test('should error if passed options invalid', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockInterceptor = new MockInterceptor({ path: '', method: '' }, []) - t.throws(() => mockInterceptor.defaultReplyHeaders(), new InvalidArgumentError('headers must be defined')) + t.assert.throws(() => mockInterceptor.defaultReplyHeaders(), new InvalidArgumentError('headers must be defined')) }) }) describe('MockInterceptor - defaultReplyTrailers', () => { test('should return MockInterceptor', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockInterceptor = new MockInterceptor({ path: '', method: '' }, []) const result = mockInterceptor.defaultReplyTrailers({}) - t.ok(result instanceof MockInterceptor) + t.assert.ok(result instanceof MockInterceptor) }) test('should error if passed options invalid', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockInterceptor = new MockInterceptor({ path: '', method: '' }, []) - t.throws(() => mockInterceptor.defaultReplyTrailers(), new InvalidArgumentError('trailers must be defined')) + t.assert.throws(() => mockInterceptor.defaultReplyTrailers(), new InvalidArgumentError('trailers must be defined')) }) }) describe('MockInterceptor - replyContentLength', () => { test('should return MockInterceptor', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockInterceptor = new MockInterceptor({ path: '', method: '' }, []) const result = mockInterceptor.defaultReplyTrailers({}) - t.ok(result instanceof MockInterceptor) + t.assert.ok(result instanceof MockInterceptor) }) }) @@ -312,7 +311,7 @@ describe('https://github.com/nodejs/undici/issues/3649', () => { ['/', '/'] ].forEach(([interceptPath, fetchedPath], index) => { test(`MockAgent should match with or without trailing slash by setting ignoreTrailingSlash as MockAgent option /${index}`, async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent({ ignoreTrailingSlash: true }) mockAgent.disableNetConnect() @@ -322,11 +321,11 @@ describe('https://github.com/nodejs/undici/issues/3649', () => { const res = await fetch(new URL(fetchedPath, 'https://localhost'), { dispatcher: mockAgent }) - t.deepStrictEqual(await res.json(), { ok: true }) + t.assert.deepStrictEqual(await res.json(), { ok: true }) }) test(`MockAgent should match with or without trailing slash by setting ignoreTrailingSlash as intercept option /${index}`, async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() mockAgent.disableNetConnect() @@ -336,7 +335,7 @@ describe('https://github.com/nodejs/undici/issues/3649', () => { const res = await fetch(new URL(fetchedPath, 'https://localhost'), { dispatcher: mockAgent }) - t.deepStrictEqual(await res.json(), { ok: true }) + t.assert.deepStrictEqual(await res.json(), { ok: true }) }) if ( @@ -344,7 +343,7 @@ describe('https://github.com/nodejs/undici/issues/3649', () => { (interceptPath === '/' && fetchedPath === '') ) { test(`MockAgent should should match on strict equal cases of paths when ignoreTrailingSlash is not set /${index}`, async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() mockAgent.disableNetConnect() @@ -354,11 +353,11 @@ describe('https://github.com/nodejs/undici/issues/3649', () => { const res = await fetch(new URL(fetchedPath, 'https://localhost'), { dispatcher: mockAgent }) - t.deepStrictEqual(await res.json(), { ok: true }) + t.assert.deepStrictEqual(await res.json(), { ok: true }) }) } else { test(`MockAgent should should reject on not strict equal cases of paths when ignoreTrailingSlash is not set /${index}`, async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() mockAgent.disableNetConnect() @@ -366,7 +365,7 @@ describe('https://github.com/nodejs/undici/issues/3649', () => { .get('https://localhost') .intercept({ path: interceptPath }).reply(200, { ok: true }) - t.rejects(fetch(new URL(fetchedPath, 'https://localhost'), { dispatcher: mockAgent })) + await t.assert.rejects(fetch(new URL(fetchedPath, 'https://localhost'), { dispatcher: mockAgent })) }) } }) @@ -405,7 +404,7 @@ describe('MockInterceptor - different payloads', () => { ['text', 'Object', 'string', { test: true }, '{"test":true}'] ].forEach(([method, inputType, outputType, input, output]) => { test(`${inputType} will be returned as ${outputType} via ${method}()`, async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() mockAgent.disableNetConnect() @@ -415,7 +414,7 @@ describe('MockInterceptor - different payloads', () => { const response = await fetch('https://localhost', { dispatcher: mockAgent }) - t.deepStrictEqual(await response[method](), output) + t.assert.deepStrictEqual(await response[method](), output) }) }) }) diff --git a/test/mock-pool.js b/test/mock-pool.js index 0febb109fcf..ec00a50cbea 100644 --- a/test/mock-pool.js +++ b/test/mock-pool.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, after, describe } = require('node:test') const { createServer } = require('node:http') const { promisify } = require('node:util') @@ -15,26 +14,26 @@ const { fetch } = require('..') describe('MockPool - constructor', () => { test('fails if opts.agent does not implement `get` method', t => { - t = tspl(t, { plan: 1 }) - t.throws(() => new MockPool('http://localhost:9999', { agent: { get: 'not a function' } }), InvalidArgumentError) + t.plan(1) + t.assert.throws(() => new MockPool('http://localhost:9999', { agent: { get: 'not a function' } }), InvalidArgumentError) }) test('sets agent', t => { - t = tspl(t, { plan: 1 }) - t.doesNotThrow(() => new MockPool('http://localhost:9999', { agent: new MockAgent() })) + t.plan(1) + t.assert.doesNotThrow(() => new MockPool('http://localhost:9999', { agent: new MockAgent() })) }) test('should implement the Dispatcher API', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockPool = new MockPool('http://localhost:9999', { agent: new MockAgent() }) - t.ok(mockPool instanceof Dispatcher) + t.assert.ok(mockPool instanceof Dispatcher) }) }) describe('MockPool - dispatch', () => { test('should handle a single interceptor', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -58,7 +57,7 @@ describe('MockPool - dispatch', () => { } ] - t.doesNotThrow(() => mockPool.dispatch({ + t.assert.doesNotThrow(() => mockPool.dispatch({ path: '/foo', method: 'GET' }, { @@ -69,7 +68,7 @@ describe('MockPool - dispatch', () => { }) test('should directly throw error from mockDispatch function if error is not a MockNotMatchedError', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -93,7 +92,7 @@ describe('MockPool - dispatch', () => { } ] - t.throws(() => mockPool.dispatch({ + t.assert.throws(() => mockPool.dispatch({ path: '/foo', method: 'GET' }, { @@ -105,7 +104,7 @@ describe('MockPool - dispatch', () => { }) test('MockPool - intercept should return a MockInterceptor', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -119,42 +118,42 @@ test('MockPool - intercept should return a MockInterceptor', (t) => { method: 'GET' }) - t.ok(interceptor instanceof MockInterceptor) + t.assert.ok(interceptor instanceof MockInterceptor) }) describe('MockPool - intercept validation', () => { test('it should error if no options specified in the intercept', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() after(() => mockAgent.close()) const mockPool = mockAgent.get('http://localhost:9999') - t.throws(() => mockPool.intercept(), new InvalidArgumentError('opts must be an object')) + t.assert.throws(() => mockPool.intercept(), new InvalidArgumentError('opts must be an object')) }) test('it should error if no path specified in the intercept', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() after(() => mockAgent.close()) const mockPool = mockAgent.get('http://localhost:9999') - t.throws(() => mockPool.intercept({}), new InvalidArgumentError('opts.path must be defined')) + t.assert.throws(() => mockPool.intercept({}), new InvalidArgumentError('opts.path must be defined')) }) test('it should default to GET if no method specified in the intercept', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockAgent = new MockAgent() after(() => mockAgent.close()) const mockPool = mockAgent.get('http://localhost:9999') - t.doesNotThrow(() => mockPool.intercept({ path: '/foo' })) + t.assert.doesNotThrow(() => mockPool.intercept({ path: '/foo' })) }) }) test('MockPool - close should run without error', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const baseUrl = 'http://localhost:9999' @@ -178,17 +177,16 @@ test('MockPool - close should run without error', async (t) => { ] await mockPool.close() - t.ok(true, 'pass') + t.assert.ok(true, 'pass') }) test('MockPool - should be able to set as globalDispatcher', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') - t.end() + t.assert.fail('should not be called') }) after(() => server.close()) @@ -200,7 +198,7 @@ test('MockPool - should be able to set as globalDispatcher', async (t) => { after(() => mockAgent.close()) const mockPool = mockAgent.get(baseUrl) - t.ok(mockPool instanceof MockPool) + t.assert.ok(mockPool instanceof MockPool) setGlobalDispatcher(mockPool) mockPool.intercept({ @@ -211,20 +209,19 @@ test('MockPool - should be able to set as globalDispatcher', async (t) => { const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.deepStrictEqual(response, 'hello') + t.assert.deepStrictEqual(response, 'hello') }) test('MockPool - should be able to use as a local dispatcher', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') - t.end() + t.assert.fail('should not be called') }) after(() => server.close()) @@ -236,7 +233,7 @@ test('MockPool - should be able to use as a local dispatcher', async (t) => { after(() => mockAgent.close()) const mockPool = mockAgent.get(baseUrl) - t.ok(mockPool instanceof MockPool) + t.assert.ok(mockPool instanceof MockPool) mockPool.intercept({ path: '/foo', @@ -247,20 +244,19 @@ test('MockPool - should be able to use as a local dispatcher', async (t) => { method: 'GET', dispatcher: mockPool }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.deepStrictEqual(response, 'hello') + t.assert.deepStrictEqual(response, 'hello') }) test('MockPool - basic intercept with MockPool.request', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') res.end('should not be called') - t.fail('should not be called') - t.end() + t.assert.fail('should not be called') }) after(() => server.close()) @@ -271,7 +267,7 @@ test('MockPool - basic intercept with MockPool.request', async (t) => { const mockAgent = new MockAgent() after(() => mockAgent.close()) const mockPool = mockAgent.get(baseUrl) - t.ok(mockPool instanceof MockPool) + t.assert.ok(mockPool instanceof MockPool) mockPool.intercept({ path: '/foo?hello=there&see=ya', @@ -288,19 +284,19 @@ test('MockPool - basic intercept with MockPool.request', async (t) => { method: 'POST', body: 'form1=data1&form2=data2' }) - t.strictEqual(statusCode, 200) - t.strictEqual(headers['content-type'], 'application/json') - t.deepStrictEqual(trailers, { 'content-md5': 'test' }) + t.assert.strictEqual(statusCode, 200) + t.assert.strictEqual(headers['content-type'], 'application/json') + t.assert.deepStrictEqual(trailers, { 'content-md5': 'test' }) const jsonResponse = JSON.parse(await getResponse(body)) - t.deepStrictEqual(jsonResponse, { + t.assert.deepStrictEqual(jsonResponse, { foo: 'bar' }) }) // https://github.com/nodejs/undici/issues/1546 test('MockPool - correct errors when consuming invalid JSON body', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const oldDispatcher = getGlobalDispatcher() @@ -316,13 +312,11 @@ test('MockPool - correct errors when consuming invalid JSON body', async (t) => }).reply(200, 'it\'s just a text') const { body } = await request('https://google.com') - await t.rejects(body.json(), SyntaxError) - - t.end() + await t.assert.rejects(body.json(), SyntaxError) }) test('MockPool - allows matching headers in fetch', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const oldDispatcher = getGlobalDispatcher() @@ -352,10 +346,10 @@ test('MockPool - allows matching headers in fetch', async (t) => { }) // no 'accept: application/json' header sent, not matched - await t.rejects(fetch(`${baseUrl}/foo`)) + await t.assert.rejects(fetch(`${baseUrl}/foo`)) // not 'accept: application/json', not matched - await t.rejects(fetch(`${baseUrl}/foo`, { + await t.assert.rejects(fetch(`${baseUrl}/foo`, { headers: { accept: 'text/plain' } @@ -363,7 +357,7 @@ test('MockPool - allows matching headers in fetch', async (t) => { }) test('MockPool - cleans mocks', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'text/plain') @@ -379,26 +373,25 @@ test('MockPool - cleans mocks', async (t) => { after(() => mockAgent.close()) const mockPool = mockAgent.get(baseUrl) - t.ok(mockPool instanceof MockPool) + t.assert.ok(mockPool instanceof MockPool) setGlobalDispatcher(mockPool) mockPool.intercept({ path: '/foo', method: 'GET' }).reply(500, () => { - t.fail('should not be called') - t.end() + t.assert.fail('should not be called') }) mockPool.cleanMocks() - t.strictEqual(mockPool[kDispatches].length, 0) + t.assert.strictEqual(mockPool[kDispatches].length, 0) const { statusCode, body } = await request(`${baseUrl}/foo`, { method: 'GET' }) - t.strictEqual(statusCode, 200) + t.assert.strictEqual(statusCode, 200) const response = await getResponse(body) - t.deepStrictEqual(response, 'hello') + t.assert.deepStrictEqual(response, 'hello') }) diff --git a/test/mock-scope.js b/test/mock-scope.js index 0344b99d0bc..ed7ffca1c29 100644 --- a/test/mock-scope.js +++ b/test/mock-scope.js @@ -1,68 +1,67 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, describe } = require('node:test') const { MockScope } = require('../lib/mock/mock-interceptor') const { InvalidArgumentError } = require('../lib/core/errors') describe('MockScope - delay', () => { test('should return MockScope', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockScope = new MockScope({ path: '', method: '' }, []) const result = mockScope.delay(200) - t.ok(result instanceof MockScope) + t.assert.ok(result instanceof MockScope) }) test('should error if passed options invalid', t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const mockScope = new MockScope({ path: '', method: '' }, []) - t.throws(() => mockScope.delay(), new InvalidArgumentError('waitInMs must be a valid integer > 0')) - t.throws(() => mockScope.delay(200.1), new InvalidArgumentError('waitInMs must be a valid integer > 0')) - t.throws(() => mockScope.delay(0), new InvalidArgumentError('waitInMs must be a valid integer > 0')) - t.throws(() => mockScope.delay(-1), new InvalidArgumentError('waitInMs must be a valid integer > 0')) + t.assert.throws(() => mockScope.delay(), new InvalidArgumentError('waitInMs must be a valid integer > 0')) + t.assert.throws(() => mockScope.delay(200.1), new InvalidArgumentError('waitInMs must be a valid integer > 0')) + t.assert.throws(() => mockScope.delay(0), new InvalidArgumentError('waitInMs must be a valid integer > 0')) + t.assert.throws(() => mockScope.delay(-1), new InvalidArgumentError('waitInMs must be a valid integer > 0')) }) }) describe('MockScope - persist', () => { test('should return MockScope', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockScope = new MockScope({ path: '', method: '' }, []) const result = mockScope.persist() - t.ok(result instanceof MockScope) + t.assert.ok(result instanceof MockScope) }) }) describe('MockScope - times', t => { test('should return MockScope', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const mockScope = new MockScope({ path: '', method: '' }, []) const result = mockScope.times(200) - t.ok(result instanceof MockScope) + t.assert.ok(result instanceof MockScope) }) test('should error if passed options invalid', t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const mockScope = new MockScope({ path: '', method: '' }, []) - t.throws(() => mockScope.times(), new InvalidArgumentError('repeatTimes must be a valid integer > 0')) - t.throws(() => mockScope.times(200.1), new InvalidArgumentError('repeatTimes must be a valid integer > 0')) - t.throws(() => mockScope.times(0), new InvalidArgumentError('repeatTimes must be a valid integer > 0')) - t.throws(() => mockScope.times(-1), new InvalidArgumentError('repeatTimes must be a valid integer > 0')) + t.assert.throws(() => mockScope.times(), new InvalidArgumentError('repeatTimes must be a valid integer > 0')) + t.assert.throws(() => mockScope.times(200.1), new InvalidArgumentError('repeatTimes must be a valid integer > 0')) + t.assert.throws(() => mockScope.times(0), new InvalidArgumentError('repeatTimes must be a valid integer > 0')) + t.assert.throws(() => mockScope.times(-1), new InvalidArgumentError('repeatTimes must be a valid integer > 0')) }) }) diff --git a/test/mock-utils.js b/test/mock-utils.js index 3ecf246c5ac..3b00242d8b7 100644 --- a/test/mock-utils.js +++ b/test/mock-utils.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, describe } = require('node:test') const { MockNotMatchedError } = require('../lib/mock/mock-errors') const { @@ -14,7 +13,7 @@ const { } = require('../lib/mock/mock-utils') test('deleteMockDispatch - should do nothing if not able to find mock dispatch', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const key = { url: 'url', @@ -23,12 +22,12 @@ test('deleteMockDispatch - should do nothing if not able to find mock dispatch', body: 'body' } - t.doesNotThrow(() => deleteMockDispatch([], key)) + t.assert.doesNotThrow(() => deleteMockDispatch([], key)) }) describe('getMockDispatch', () => { test('it should find a mock dispatch', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const dispatches = [ { path: 'path', @@ -41,7 +40,7 @@ describe('getMockDispatch', () => { path: 'path', method: 'method' }) - t.deepStrictEqual(result, { + t.assert.deepStrictEqual(result, { path: 'path', method: 'method', consumed: false @@ -49,7 +48,7 @@ describe('getMockDispatch', () => { }) test('it should skip consumed dispatches', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const dispatches = [ { path: 'path', @@ -67,7 +66,7 @@ describe('getMockDispatch', () => { path: 'path', method: 'method' }) - t.deepStrictEqual(result, { + t.assert.deepStrictEqual(result, { path: 'path', method: 'method', consumed: false @@ -75,7 +74,7 @@ describe('getMockDispatch', () => { }) test('it should throw if dispatch not found', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const dispatches = [ { path: 'path', @@ -84,14 +83,14 @@ describe('getMockDispatch', () => { } ] - t.throws(() => getMockDispatch(dispatches, { + t.assert.throws(() => getMockDispatch(dispatches, { path: 'wrong', method: 'wrong' }), new MockNotMatchedError('Mock dispatch not matched for path \'wrong\'')) }) test('it should throw if no dispatch matches method', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const dispatches = [ { path: 'path', @@ -100,14 +99,14 @@ describe('getMockDispatch', () => { } ] - t.throws(() => getMockDispatch(dispatches, { + t.assert.throws(() => getMockDispatch(dispatches, { path: 'path', method: 'wrong' }), new MockNotMatchedError('Mock dispatch not matched for method \'wrong\' on path \'path\'')) }) test('it should throw if no dispatch matches body', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const dispatches = [ { path: 'path', @@ -117,7 +116,7 @@ describe('getMockDispatch', () => { } ] - t.throws(() => getMockDispatch(dispatches, { + t.assert.throws(() => getMockDispatch(dispatches, { path: 'path', method: 'method', body: 'wrong' @@ -125,7 +124,7 @@ describe('getMockDispatch', () => { }) test('it should throw if no dispatch matches headers', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const dispatches = [ { path: 'path', @@ -136,7 +135,7 @@ describe('getMockDispatch', () => { } ] - t.throws(() => getMockDispatch(dispatches, { + t.assert.throws(() => getMockDispatch(dispatches, { path: 'path', method: 'method', body: 'body', @@ -147,44 +146,44 @@ describe('getMockDispatch', () => { describe('getResponseData', () => { test('it should stringify objects', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const responseData = getResponseData({ str: 'string', num: 42 }) - t.strictEqual(responseData, '{"str":"string","num":42}') + t.assert.strictEqual(responseData, '{"str":"string","num":42}') }) test('it should return strings untouched', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const responseData = getResponseData('test') - t.strictEqual(responseData, 'test') + t.assert.strictEqual(responseData, 'test') }) test('it should return buffers untouched', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const responseData = getResponseData(Buffer.from('test')) - t.ok(Buffer.isBuffer(responseData)) + t.assert.ok(Buffer.isBuffer(responseData)) }) test('it should return Uint8Array untouched', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const responseData = getResponseData(new TextEncoder().encode('{"test":true}')) - t.ok(responseData instanceof Uint8Array) + t.assert.ok(responseData instanceof Uint8Array) }) test('it should return ArrayBuffers untouched', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const responseData = getResponseData(new TextEncoder().encode('{"test":true}').buffer) - t.ok(responseData instanceof ArrayBuffer) + t.assert.ok(responseData instanceof ArrayBuffer) }) test('it should handle undefined', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const responseData = getResponseData(undefined) - t.strictEqual(responseData, '') + t.assert.strictEqual(responseData, '') }) }) test('getStatusText', (t) => { - t = tspl(t, { plan: 64 }) + t.plan(64) for (const statusCode of [ 100, 101, 102, 103, 200, 201, 202, 203, @@ -196,28 +195,26 @@ test('getStatusText', (t) => { 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511 ]) { - t.ok(getStatusText(statusCode)) + t.assert.ok(getStatusText(statusCode)) } - t.strictEqual(getStatusText(420), 'unknown') - - t.end() + t.assert.strictEqual(getStatusText(420), 'unknown') }) test('getHeaderByName', (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const headersRecord = { key: 'value' } - t.strictEqual(getHeaderByName(headersRecord, 'key'), 'value') - t.strictEqual(getHeaderByName(headersRecord, 'anotherKey'), undefined) + t.assert.strictEqual(getHeaderByName(headersRecord, 'key'), 'value') + t.assert.strictEqual(getHeaderByName(headersRecord, 'anotherKey'), undefined) const headersArray = ['key', 'value'] - t.strictEqual(getHeaderByName(headersArray, 'key'), 'value') - t.strictEqual(getHeaderByName(headersArray, 'anotherKey'), undefined) + t.assert.strictEqual(getHeaderByName(headersArray, 'key'), 'value') + t.assert.strictEqual(getHeaderByName(headersArray, 'anotherKey'), undefined) const { Headers } = require('../index') @@ -225,51 +222,49 @@ test('getHeaderByName', (t) => { ['key', 'value'] ]) - t.strictEqual(getHeaderByName(headers, 'key'), 'value') - t.strictEqual(getHeaderByName(headers, 'anotherKey'), null) - - t.end() + t.assert.strictEqual(getHeaderByName(headers, 'key'), 'value') + t.assert.strictEqual(getHeaderByName(headers, 'anotherKey'), null) }) describe('buildHeadersFromArray', () => { test('it should build headers from array', (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const headers = buildHeadersFromArray([ 'key', 'value' ]) - t.deepStrictEqual(Object.keys(headers).length, 1) - t.strictEqual(headers.key, 'value') + t.assert.deepStrictEqual(Object.keys(headers).length, 1) + t.assert.strictEqual(headers.key, 'value') }) }) describe('normalizeQueryParams', () => { test('it should handle basic cases', (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) - t.deepStrictEqual(normalizeSearchParams('').toString(), '') - t.deepStrictEqual(normalizeSearchParams('a').toString(), 'a=') - t.deepStrictEqual(normalizeSearchParams('b=2&c=3&a=1').toString(), 'b=2&c=3&a=1') - t.deepStrictEqual(normalizeSearchParams('lang=en_EN&id=123').toString(), 'lang=en_EN&id=123') + t.assert.deepStrictEqual(normalizeSearchParams('').toString(), '') + t.assert.deepStrictEqual(normalizeSearchParams('a').toString(), 'a=') + t.assert.deepStrictEqual(normalizeSearchParams('b=2&c=3&a=1').toString(), 'b=2&c=3&a=1') + t.assert.deepStrictEqual(normalizeSearchParams('lang=en_EN&id=123').toString(), 'lang=en_EN&id=123') }) // https://github.com/nodejs/undici/issues/4146 test('it should handle multiple values set using different syntaxes', (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) - t.deepStrictEqual(normalizeSearchParams('a=1&a=2&a=3').toString(), 'a=1&a=2&a=3') - t.deepStrictEqual(normalizeSearchParams('a[]=1&a[]=2&a[]=3').toString(), 'a=1&a=2&a=3') - t.deepStrictEqual(normalizeSearchParams('a=1,2,3').toString(), 'a=1&a=2&a=3') + t.assert.deepStrictEqual(normalizeSearchParams('a=1&a=2&a=3').toString(), 'a=1&a=2&a=3') + t.assert.deepStrictEqual(normalizeSearchParams('a[]=1&a[]=2&a[]=3').toString(), 'a=1&a=2&a=3') + t.assert.deepStrictEqual(normalizeSearchParams('a=1,2,3').toString(), 'a=1&a=2&a=3') }) test('should handle edge case scenarios', (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) - t.deepStrictEqual(normalizeSearchParams('a="b[]"').toString(), `a=${encodeURIComponent('"b[]"')}`) - t.deepStrictEqual(normalizeSearchParams('a="1,2,3"').toString(), `a=${encodeURIComponent('"1,2,3"')}`) + t.assert.deepStrictEqual(normalizeSearchParams('a="b[]"').toString(), `a=${encodeURIComponent('"b[]"')}`) + t.assert.deepStrictEqual(normalizeSearchParams('a="1,2,3"').toString(), `a=${encodeURIComponent('"1,2,3"')}`) const encodedSingleQuote = '%27' - t.deepStrictEqual(normalizeSearchParams("a='b[]'").toString(), `a=${encodedSingleQuote}${encodeURIComponent('b[]')}${encodedSingleQuote}`) - t.deepStrictEqual(normalizeSearchParams("a='1,2,3'").toString(), `a=${encodedSingleQuote}${encodeURIComponent('1,2,3')}${encodedSingleQuote}`) + t.assert.deepStrictEqual(normalizeSearchParams("a='b[]'").toString(), `a=${encodedSingleQuote}${encodeURIComponent('b[]')}${encodedSingleQuote}`) + t.assert.deepStrictEqual(normalizeSearchParams("a='1,2,3'").toString(), `a=${encodedSingleQuote}${encodeURIComponent('1,2,3')}${encodedSingleQuote}`) }) })