js-libp2p-tcp/test/connection.spec.js

56 lines
1.3 KiB
JavaScript
Raw Normal View History

2018-02-07 05:56:55 +00:00
/* eslint-env mocha */
'use strict'
const chai = require('chai')
const dirtyChai = require('dirty-chai')
const expect = chai.expect
chai.use(dirtyChai)
2019-04-12 15:53:17 +08:00
const TCP = require('../src')
2018-02-07 05:56:55 +00:00
const multiaddr = require('multiaddr')
describe('valid Connection', () => {
let tcp
beforeEach(() => {
tcp = new TCP()
})
const ma = multiaddr('/ip4/127.0.0.1/tcp/9090')
2019-04-12 15:53:17 +08:00
it('get observed addrs', async () => {
// Create a Promise that resolves when a connection is handled
let handled
const handlerPromise = new Promise((resolve) => {
handled = resolve
2018-02-07 05:56:55 +00:00
})
2019-04-12 15:53:17 +08:00
const handler = async (conn) => {
2018-02-07 05:56:55 +00:00
expect(conn).to.exist()
2019-04-12 15:53:17 +08:00
const dialerObsAddrs = await conn.getObservedAddrs()
handled(dialerObsAddrs)
}
2018-02-07 05:56:55 +00:00
2019-04-12 15:53:17 +08:00
// Create a listener with the handler
const listener = tcp.createListener(handler)
2018-02-07 05:56:55 +00:00
2019-04-12 15:53:17 +08:00
// Listen on the multi-address
await listener.listen(ma)
2018-02-07 05:56:55 +00:00
2019-04-12 15:53:17 +08:00
// Dial to that same address
const conn = await tcp.dial(ma)
const addrs = await conn.getObservedAddrs()
2018-02-07 05:56:55 +00:00
2019-04-12 15:53:17 +08:00
// Wait for the incoming dial to be handled
const dialerObsAddrs = await handlerPromise
2018-02-07 05:56:55 +00:00
2019-04-12 15:53:17 +08:00
// Close the listener
await listener.close()
2018-02-07 05:56:55 +00:00
2019-04-12 15:53:17 +08:00
// The addresses should match
expect(addrs.length).to.equal(1)
expect(addrs[0]).to.deep.equal(ma)
expect(dialerObsAddrs.length).to.equal(1)
expect(dialerObsAddrs[0]).to.exist()
2018-02-07 05:56:55 +00:00
})
})