0

I have an async method triggered by a click event where I make a call to an API and then process the response, like this:

async confirmName () {
    const {name, description} = this.form;
    const [data, error] = await Pipelines.createPipeline({name, description});

    if (error) {
        console.error(error);
        this.serviceError = true;
        return false;
    }

    this.idPipelineCreated = data.pipeline_id;
    return true;
}

The test looks like this:

test("API success", async () => {
    const ConfirmNameBtn = wrapper.find(".form__submit-name");
    await ConfirmNameBtn.vm.$emit("click");

    const pipelinesApi = new Pipelines();
    jest.spyOn(pipelinesApi, "createPipeline").mockResolvedValue({pipeline_id: 100});

    const {name, description} = wrapper.vm.form;

    pipelinesApi.createPipeline().then(data => {
        expect(wrapper.vm.pipelineNameServiceError).toBe(false);

        wrapper.setData({
            idPipelineCreated: data.pipeline_id
        });

        expect(wrapper.vm.idPipelineCreated).toBe(data.pipeline_id)
    }).catch(() => {})

})

A basic class mock:

export default class Pipelines {
    constructor () {}

    createPipeline () {}
}

I'm testing a success API call and I mock the API call returning a resolved promised. The problem is the coverage only covers the first two lines of the method, not the part where I assign the response of the API call. Is this the correct approach?

Edit:

Screenshot of coverage report:

enter image description here

Ismael Ordás
  • 370
  • 4
  • 12

1 Answers1

0

Don't mix up await and then/catch. Prefer using await unless you have very special cases (see this answer):

test("API success", async () => {
    const ConfirmNameBtn = wrapper.find(".form__submit-name");
    await ConfirmNameBtn.vm.$emit("click");

    const pipelinesApi = new Pipelines();
    jest.spyOn(pipelinesApi, "createPipeline").mockResolvedValue({pipeline_id: 100});

    const {name, description} = wrapper.vm.form;
    const data = await pipelinesApi.createPipeline();

    expect(wrapper.vm.pipelineNameServiceError).toBe(false);

    wrapper.setData({
        idPipelineCreated: data.pipeline_id
    });

    expect(wrapper.vm.idPipelineCreated).toBe(data.pipeline_id)
    expect(wrapper.vm.serviceError).toBe(false);
})
Anatoly
  • 20,799
  • 3
  • 28
  • 42