Search code examples
resttestingcucumberjs

Pactumjs - Cucumber: store token from response


I'm new to Pactumjs. I have a problem in a cucumber step when I want to store my bearer token to reuse it in another cucumber step.

Given('I call the login service', async () => {
    await pactum.spec()
        .post('/api/rest/login')
        .withHeaders('Content-Type', 'application/json')
        .withBody({
            file: "json/login.json"
        })
        .expectStatus(200)
        .expect(ctx => {
            const token = ctx.res.body.token;
            chai.expect(token).is.not.null;
        });
});

When('I call the get points of sale service', async function () {
    await pactum.spec()
        .get('/api/rest/admin)
        .withHeaders({
            'Authorization': 'Bearer ',  // MY TOKEN
            'Content-Type': 'application/json'
        })
        .expectStatus(200);
});

I've trid also to use the 'stores' command with no results.

How could I do? Can anyone help me?


Solution

  • Ideally stores should work as expected.

    const { string } = require('pactum-matchers');
    
    Given('I call the login service', async () => {
        await pactum.spec()
            .post('/api/rest/login')
            .withHeaders('Content-Type', 'application/json')
            .withBody({
                file: "json/login.json"
            })
            .expectStatus(200)
            .expectJsonMatch({
              "token": string()
            })
            .stores('TOKEN', 'token');
    });
    
    When('I call the get points of sale service', async function () {
        await pactum.spec()
            .get('/api/rest/admin')
            .withHeaders({
                'Authorization': 'Bearer $S{TOKEN}',
                'Content-Type': 'application/json'
            })
            .expectStatus(200);
    });