0

I have a getter: defaultInternalAccountId and I am watching this property in my component. When it changes, I call a method: fetchAccount, which is also called when the component is mounted. I need to create a test that asserts that it was called twice and that the second time it was called with the correct accountId. Here's an attempt:

test('Dispatches fetchAccount when defaultInternalAccountId is updated', () => {
    const accountId = '1234';
    const accountId2 = '5678';
    mockDefaultInternalAccountId.mockReturnValueOnce(accountId);
    mockDefaultInternalAccountId.mockReturnValueOnce(accountId2);

    const wrapper = shallowMount(AssetAllocationsSummaryContainer, {
        localVue,
        store,
    });

    expect(mockFetchAccount.mock.calls[0][1]).toEqual({ accountId }); // There are other args that mapActions applies

    wrapper.vm.$nextTick();
    expect(mockFetchAccount).toHaveBeenCalledTimes(2);
    expect(mockFetchAccount.mock.calls[1][1]).toEqual({ accountId: accountId2 }); // There are other args that mapActions applies
});

The above is failing at expect(mockFetchAccount).toHaveBeenCalledTimes(2); as mockFetchAccount is only being called once. Here is the watcher:

watch: {
  defaultInternalAccountId: {
      immediate: true,
      handler(newAccountId, oldAccountId) {
          if (newAccountId && newAccountId !== oldAccountId) {
              this.fetchAccount({ accountId: newAccountId });
          }
      },
  },
},

defaultInternalAccountId is a mapped getter: ...mapGetters(['defaultInternalAccountId']), and fetchAccount is a mapped action: ...mapActions(['fetchAccount']),. All is working as expected in vivo. I have also attempted setting state directly, but the component does not pick up on that change: store.state.defaultInternalAccountId = accountId2

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Matt Larsuma
  • 1,456
  • 4
  • 20
  • 52

1 Answers1

0

Getters are cached so I needed to implement the mock getter using reactive state instead of mockReturnValue:

test('Dispatches fetchAccount when defaultInternalAccountId is updated', () => {
  const accountId = '1234';
  const accountId2 = '5678';
  const vm = new Vue({ data: { accountId } });

  mockDefaultInternalAccountId.mockImplementation(() => vm.accountId);

  shallowMount(AssetAllocationsSummaryContainer, {
    localVue,
    store,
  });

  expect(mockFetchAccount.mock.calls[0][1]).toEqual({ accountId });

  vm.accountId = accountId2;

  expect(mockFetchAccount).toHaveBeenCalledTimes(2);
  expect(mockFetchAccount.mock.calls[1][1]).toEqual({ accountId: accountId2 });
});
Matt Larsuma
  • 1,456
  • 4
  • 20
  • 52