mardi 2 février 2021

VueJS testing with chai and awaiting .trigger('click')

I am learning to use Chai in the context of a VueJS app.

in the browser, the app works as expected. In the test, my issue is that after I click a button I want to check that the screen has updated with the result of a @btnClick method.

The test always shows that no value exists in the element. If I hard code a value in the element, the test finds it, so it seems like some sort of promise issue.

Here is the component I am testing

<template>
  <div>
    The Anwwer to 
    <span>
      <input class="number" type="number" data-unit="number1" data-e2e="number1" v-model="number1">
    </span>
    +
    <span>
      <input class="number" type="number" data-unit="number2" data-e2e="number2" v-model="number2">
    </span>
    =
    <span class="answer" data-unit="answer" data-e2e="answer">
      
    </span>
    <div>
      <button class="button" data-unit="btn" data-e2e="btn" @click="doCalc">Get Answer</button>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      number1: null,
      number2: null,
      answer: null
    }
  },
  methods: {
    doCalc() {
      console.log("********************** Calc button clicked ************************")
      this.answer = parseInt(this.number1) + parseInt(this.number2)
    }
  }
}
</script>

and here is my test

describe('Calculator.vue', () => {
  it('renders 4 when adding 2 + 2', async () => {
    const number1 = 2
    const number2 = 2
    const answer = 4
    const wrapper = shallowMount(Calculator)
    var input1 = wrapper.find("[data-unit='number1']")
    var input2 = wrapper.find("[data-unit='number2']")
    var resultText = wrapper.find(".answer");
    input1.value = number1
    input2.value = number2
    wrapper.find("button").trigger("click")
    expect(resultText.text()).to.contain(answer);
  });
});

and here is the result of the test

Calculator.vue
********************** Calc button clicked ************************
1) Calculator.vue
       renders 4 when adding 2 + 2:
     AssertionError: expected '' to include 4
      at Context.<anonymous> (dist/js/webpack:/tests/unit/calculator.spec.js:17:1)
      at processImmediate (internal/timers.js:439:21)

Aucun commentaire:

Enregistrer un commentaire