mercredi 10 avril 2019

Mocha testing, why do I have to use 'this' to reference functions on same page but not in TS?

Is there a workaround in Mocha / Sinon to not change code to write a test? We have this code in production headers.ts file and it has methods that reference other methods in the same file. The code works, but I am not able to write a test without updating the code.

export function hidePoweredBy(res: Response) {
    res.app.disable('x-powered-by')
    res.removeHeader('Server')
}

export function frameguard(res: Response) {
    res.setHeader('X-Frame-Options', 'SAMEORIGIN')
}
export function securityHeaders(req: Request, res: Response, next: any) {
    frameguard(res)
    nocache(res)
    hidePoweredBy(res)
    next()
}

Spec file for the method

    describe('securityHeaders', () => {
        it('Should call all methods in securityHeaders', () => {

            const sandbox = sinon.createSandbox()
            sandbox.stub(securityHeaders, 'frameguard')
            sandbox.stub(securityHeaders, 'nocache')
            sandbox.stub(securityHeaders, 'hidePoweredBy')

            const req = mockReq()
            const res = mockRes()
            const spy = sinon.spy()

            securityHeaders.securityHeaders(req, res, spy )

            expect(securityHeaders.frameguard).to.have.been.called
            expect(securityHeaders.nocache).to.have.been.called
            expect(securityHeaders.hidePoweredBy).to.have.been.called


            sandbox.restore()

        })
    })

For me to write a test that work I need to reference the methods to have 'this' as scope.

export function hidePoweredBy(res: Response) {
    res.app.disable('x-powered-by')
    res.removeHeader('Server')
}

export function frameguard(res: Response) {
    res.setHeader('X-Frame-Options', 'SAMEORIGIN')
}
export function securityHeaders(req: Request, res: Response, next: any) {
    this.frameguard(res)
    this.nocache(res)
    this.hidePoweredBy(res)
    next()
}

Is there a workaround without me changing code and just a test ?

Aucun commentaire:

Enregistrer un commentaire