Mocking a Koa Context
See original GitHub issueI didn’t find any pre-existing issues, so I figured I’d open this for discussion. I’m looking for an easier way to mock a Context
object in order to unit test routes/middleware in isolation without having to spin up and teardown an http server to do so.
Consider this trivial example:
authenticate.ts
import { Context } from 'koa';
export default function() {
return async function(ctx: Context) {
ctx.assert(ctx.headers.completelySecure === 'OPEN THE DOOR', 401, 'Unauthenticated. What\'s the secret word?');
};
}
authenticate.spec.ts
import authenticate from './authenticate';
describe('Authenticate', function() {
it('totally works', async function(done) {
const authenticator = authenticate();
// Sadness, this does not implement `context` and there is no easy way
// to do so
const mockContext = {
headers: {
completelySecure: 'OPEN THE DOOR'
}
};
try {
await authenticator(mockContext);
done();
} catch(err) {
done.fail();
}
});
});
What I’m proposing is to support creation of mock contexts either in the core library, or another closely held project since it’s highly likely that something like this would need to depend on internals of the library.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:5
- Comments:5 (2 by maintainers)
Top Results From Across the Web
How to mock koa context in a function that returns a function ...
I use Shopify's library @shopify/jest-koa-mocks. They use Koa's createContext under the hood if you want to explore building it yourself.
Read more >@shopify/jest-koa-mocks - npm
Utilities to easily stub Koa context and cookies. Latest version: 5.0.1, last published: 4 months ago. Start using @shopify/jest-koa-mocks ...
Read more >Async testing Koa with Jest - Medium
The context object is a mock. We could provide other data like requested URL or headers.
Read more >Koa-create-context - npm.io
Create a context for mocking or whatever purpose. Installation. yarn. Usage. import createContext from "koa-create-context" ...
Read more >koa-mock | Yarn - Package Manager
koa -mock. NPM version build status Test coverage David deps npm download. Web page mock middleware. Features. Simple url and mock file mapping...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@dcherman it’s not public because there’s not really a point of mocking when it’s really simple to just test an actual koa app. we also don’t want people extending it too much and adding “globals” because we see that as an anti-pattern
Future Google visitors: Shopify made a thing