1

I have one Users vue component and I am trying to test mounted() with addEventListener.

 Users.vue
 =========
 
 mounted(){
 
 let viewPort = document.getElementById("Users-list"); ----> Here I am getting null for addEventListener.
    viewPort!.addEventListener("scroll", (e: any) => { 
      let result =
        e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight ===
        0;
      if (result) {
        this.test = this.Offset + this.Limit;
        this.response = this.GetDetails();
      }
    });
}

I have written spec for Users component and trying to test mounted() method with addEventListener. But I am getting an error message cannot read property addEventListener of null.

Users.spec.ts
=============
describe('Users TestSuite', async () => {

  let userWrapper: any;
  let userObj: any;
  beforeEach(() => {
    userWrapper = shallowMount(Users, {
     // attachTo: document.getElementById('Users-list'),
      localVue,
      i18n,
      router
    })
    userObj = userWrapper.findComponent(Users).vm;
    const mockAddeventListener = jest.fn().mockImplementation((event, fn) => {
        fn();
      })
      document.getElementById = jest.fn().mockReturnValue({
        scrollTop: 100,
        clientHeight: 200,
        scrollHeight: 500,
        addEventListener: mockAddeventListener
      })
     expect(mockAddeventListener).toBeCalledWith('scroll', expect.anything());
 });
 
 it('should render Users page', () => {
    expect(userObj).toBeTruthy();  
  });
Lin Du
  • 88,126
  • 95
  • 281
  • 483
Sapthika
  • 31
  • 1
  • 4

1 Answers1

1
  1. I think the problem here might be u are creating the mock function after u are creating the component. Mounted method will be called when the wrapper is created so try to move the mock implementation above the wrapper statement.

  2. Another sure way in which to make it work is before u create the wrapper set the body of the document like document.body.innerHTML = <div id="users-list"></div>. This will definitely work.

For both the above solutions make sure that they are above the wrapper statement.

Vignesh V
  • 11
  • 1