Last active
September 25, 2017 10:46
-
-
Save poetix/063129c6ed1427f0fa9a9b1e9a5443a0 to your computer and use it in GitHub Desktop.
Unit testing an endpoint class with a mocked service class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { expect } from 'chai'; | |
import 'mocha'; | |
class HelloEndpoint { | |
constructor(private service: HelloService) {} | |
async handle(evt: any): Promise<any> { | |
const greeting = await this.service.sayHello(evt.queryStringParameters.name); | |
return { | |
statusCode: 200, | |
body: greeting | |
}; | |
} | |
} | |
interface HelloService { | |
sayHello(name: string): Promise<string> | |
} | |
class TestHelloService implements HelloService { | |
receivedName?: string; | |
async sayHello(name: string): Promise<string> { | |
this.receivedName = name; | |
return `Hello ${name}!`; | |
} | |
} | |
const helloService = new TestHelloService(); | |
const helloEndpoint = new HelloEndpoint(helloService); | |
describe("The Hello Endpoint", () => { | |
it("Should greet the person", async () => { | |
// Call the endpoint. | |
const result = await helloEndpoint.handle({ | |
queryStringParameters: { | |
name: "Arthur Putey" | |
} | |
}); | |
// Validate that the right data is passed into the service. | |
expect(helloService.receivedName).to.equal("Arthur Putey"); | |
// Validate that the right response is returned to the client. | |
expect(result.body).to.equal("Hello Arthur Putey!"); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment