Search code examples
typescriptvue.jsunit-testing

Vue Unit test Input value not set


I am using Vue with typescript and attempting a unit test of the input value for a login page. The test sets the input value, then checks that the value equals what was entered, except the value checked is coming back empty "" and I cannot figure out why.

Homepage.vue:

<form class="form" @submit.prevent="submit">
        <input
          id="userNameTextInput"
          v-model="username"
          placeholder="Name"
          minlength="2"
        /><br />
        <input
          id="passwordTextInput"
          type="password"
          v-model="password"
          placeholder="Password"
          minlength="8"
        /><br />
        <button
          id="submitButton"
          color="white"
          background="darkslateblue"
          type="submit"
          @click="submit"
        >
          Submit
        </button>
        <div id="incorrectLoginBlock" v-show="toggleIncorrectLogin">
          <p>Incorrect Membername or Password</p>
        </div>
      </form>

Homepage.spec.ts:

import HomePage from '@/components/HomePage.vue';
import {mount, VueWrapper} from '@vue/test-utils';

describe('HomePage.vue', () => {
  let wrapper: VueWrapper<any>;

  beforeEach(() => {
    wrapper = mount(HomePage);
  });

  it('Incorrect login pops up', async () => {
        const userTextInputIncorrect = wrapper.find('#userNameTextInput');
        userTextInputIncorrect.setValue('wrongPass');
        expect(userTextInputIncorrect.element.textContent).toContain(
        'incorrectName',
    );

The Error:

expect(received).toContain(expected) // indexOf

Expected substring: "incorrectName"

Received string: ""

const userTextInputIncorrect = wrapper.find('#userNameTextInput');

userTextInputIncorrect.setValue('wrongPass');

expect(userTextInputincorrect.element.textContent).toBe('incorrectName');


Solution

  • It should work:

    it("Incorrect login pops up", async () => {
      const userTextInputIncorrect = wrapper.find("#userNameTextInput");
      await userTextInputIncorrect.setValue("wrongPass");
    
      expect(
        (userTextInputIncorrect.element as HTMLInputElement).value
      ).toContain("incorrectName");
    });