Skip to content

Commit

Permalink
Merge pull request #6 from bergos/esm
Browse files Browse the repository at this point in the history
feat: switched to esm, updated deps & ci
  • Loading branch information
bergos authored Mar 18, 2024
2 parents e102cd9 + df78923 commit bbafbd4
Show file tree
Hide file tree
Showing 12 changed files with 206 additions and 170 deletions.
19 changes: 0 additions & 19 deletions .github/workflows/ci.yaml

This file was deleted.

21 changes: 21 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Test
on:
- pull_request
- push
jobs:
test:
runs-on: ubuntu-20.04
strategy:
matrix:
node:
- '18'
- '20'
- '21'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node }}
- run: npm install
- run: npm test
- uses: codecov/codecov-action@v3
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
.idea
coverage
node_modules
package-lock.json
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Thomas Bergwinkl

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
62 changes: 36 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# express-as-promise

ExpressAsPromise is a simple Promise wrapper for [Express](http://expressjs.com/).
[![build status](https://img.shields.io/github/actions/workflow/status/bergos/express-as-promise/test.yaml?branch=master)](https://github.com/bergos/express-as-promise/actions/workflows/test.yaml)
[![npm version](https://img.shields.io/npm/v/express-as-promise.svg)](https://www.npmjs.com/package/express-as-promise)

ExpressAsPromise is a simple Promise wrapper for [Express](https://expressjs.com/).
It also adds some convenient methods & properties which are especially useful for testing.

## Usage
Expand All @@ -20,39 +23,25 @@ The `.url` property contains a string to the base URL.
Returns the base URL as string.
- `async stop()`: Stops the listener.

### Static Methods

- `withServer(callback)`: Creates a server instance and hands it over to an async callback function.
Once the callback function finished with resolve or reject, it stops the server and forwards the error if it finished with reject.
This method is intended for testing using a pattern like this:

```javascript
const { withServer } = require('express-as-promise')

it('should handle my test case', async () => {
await withServer(async server => {
server.app.use(myMiddleware)

const url = await server.listen()

const res = await fetch(url)

strictEqual(res.status, 200)
})
})
```

### Properties

- `.app`: The actual express object.
- `.url`: The base URL of the listener.

## Example
### withServer

The `withServer` function can be imported from `express-as-promise/withServer.js`.
It creates a server instance and hands it over to an async callback function.
Once the callback function finished with resolve or reject, it stops the server and forwards the error if it finished with reject.
This function is intended for testing using a pattern like shown in the examples below.

## Examples

Simple example which adds one route, starts the server, write the base URL to the console and waits 10s before it stops the server.

```javascript
const ExpressAsPromise = require('express-as-promise')
import { setTimeout } from 'node:timers/promises'
import ExpressAsPromise from 'express-as-promise'

async function main () {
// creates a new instance which also creates an express object
Expand All @@ -66,12 +55,33 @@ async function main () {
console.log(await server.listen())

// wait 10s...
await (new Promise(resolve => setTimeout(resolve, 10000)))
await setTimeout(10000)

// ...then stop the server
await server.stop()
}

main()
```

The following example starts a server with `withServer`, adds a route, makes a request.
Once the function is finished, the server is automatically stopped.

```javascript
import withServer from 'express-as-promise/withServer.js'

async function main () {
await withServer(async server => {
server.app.get('/test', (req, res) => {
res.end('test response')
})

const res = await server.fetch('/test')
const content = await res.text()

console.log(content)
})
}

main()
```
5 changes: 3 additions & 2 deletions examples/simple.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const ExpressAsPromise = require('..')
import { setTimeout } from 'node:timers/promises'
import ExpressAsPromise from '../index.js'

async function main () {
// creates a new instance which also creates an express object
Expand All @@ -12,7 +13,7 @@ async function main () {
console.log(await server.listen())

// wait 10s...
await (new Promise(resolve => setTimeout(resolve, 10000)))
await setTimeout(10000)

// ...then stop the server
await server.stop()
Expand Down
2 changes: 1 addition & 1 deletion examples/withServer.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { withServer } = require('..')
import withServer from '../withServer.js'

async function main () {
await withServer(async server => {
Expand Down
30 changes: 4 additions & 26 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
const express = require('express')
const fetch = require('node-fetch')
const { promisify } = require('util')
import { promisify } from 'node:util'
import express from 'express'
import fetch from 'node-fetch'

class ExpressAsPromise {
constructor () {
this.app = express()
this.server = null

this._listen = null
}

async listen (port, host) {
Expand Down Expand Up @@ -61,26 +59,6 @@ class ExpressAsPromise {
get url () {
return `http://${this.host}${this.port !== 80 ? `:${this.port}` : ''}/`
}

static async withServer (callback) {
const server = new ExpressAsPromise()

let error = null

try {
await callback(server)
} catch (err) {
error = err
}

if (server.server) {
await server.stop()
}

if (error) {
throw error
}
}
}

module.exports = ExpressAsPromise
export default ExpressAsPromise
15 changes: 8 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
"name": "express-as-promise",
"version": "1.2.0",
"description": "Simple Promise wrapper for Express",
"type": "module",
"main": "index.js",
"scripts": {
"test": "standard && mocha"
"test": "stricter-standard && c8 --reporter=lcov --reporter=text-summary mocha"
},
"repository": {
"type": "git",
"url": "git://github.com/bergos/express-as-promise.git"
"url": "https://github.com/bergos/express-as-promise.git"
},
"keywords": [
"express",
Expand All @@ -21,12 +22,12 @@
},
"homepage": "https://github.com/bergos/express-as-promise",
"dependencies": {
"express": "^4.16.4",
"node-fetch": "^2.6.1"
"express": "^4.18.3",
"node-fetch": "^3.3.2"
},
"devDependencies": {
"mocha": "^7.1.2",
"promise-the-world": "^1.0.1",
"standard": "^14.3.3"
"c8": "^9.1.0",
"mocha": "^10.3.0",
"stricter-standard": "^0.3.1"
}
}
90 changes: 4 additions & 86 deletions test/ExpressAsPromise.test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
const { notStrictEqual, strictEqual } = require('assert')
const { describe, it } = require('mocha')
const fetch = require('node-fetch')
const { delay } = require('promise-the-world')
const ExpressAsPromise = require('..')
import { notStrictEqual, strictEqual } from 'node:assert'
import { describe, it } from 'mocha'
import fetch from 'node-fetch'
import ExpressAsPromise from '../index.js'

describe('ExpressAsPromise', () => {
it('should be a constructor', () => {
Expand Down Expand Up @@ -152,85 +151,4 @@ describe('ExpressAsPromise', () => {
await server.stop()
})
})

describe('.withServer', () => {
it('should be a static method', () => {
strictEqual(typeof ExpressAsPromise.withServer, 'function')
})

it('should call the given callback function', async () => {
let called = false

await ExpressAsPromise.withServer(() => {
called = true
})

strictEqual(called, true)
})

it('should wait for the callback', async () => {
let finish = false
let finished = false

ExpressAsPromise.withServer(async () => {
while (!finish) { // eslint-disable-line no-unmodified-loop-condition
await delay(1)
}
}).then(() => {
finished = true
})

strictEqual(finished, false)

finish = true
await delay(10)

strictEqual(finished, true)
})

it('should create a ExpressAsPromise object and forward it to the callback', async () => {
let instance = null

await ExpressAsPromise.withServer(arg => {
instance = arg
})

strictEqual(instance instanceof ExpressAsPromise, true)
})

it('should forward any error thrown by the callback', async () => {
let error = null

try {
await ExpressAsPromise.withServer(() => {
throw new Error()
})
} catch (err) {
error = err
}

strictEqual(error instanceof Error, true)
})

it('should create a ExpressAsPromise object and forward it to the callback', async () => {
let instance = null

await ExpressAsPromise.withServer(arg => {
instance = arg
})

strictEqual(instance instanceof ExpressAsPromise, true)
})

it('should stop the server if it was started', async () => {
let instance = null

await ExpressAsPromise.withServer(async arg => {
instance = arg
await instance.listen()
})

strictEqual(instance.server, null)
})
})
})
Loading

0 comments on commit bbafbd4

Please sign in to comment.