简体   繁体   中英

Mocking a method on "this" object in jest

I have the following implementation:

export const actions = {
  async submitPhoneNumber(context) {
    let data = await this.$axios.
        $get('https://jsonplaceholder.typicode.com/todos/1')
    // do something with data
    return data

  }
}

When I run my test I get

TypeError: Cannot read property '$get' of undefined

How do I mock this.$axios.$get ?

I looked at mocking global in jest but mocking global is just mocking window.whatever.

I need to mock this object.

This is my test:

import { actions } from '@/store/channel-add'
import flushPromises from 'flush-promises'
describe('channel-add', () => {
  it('submits phone number and returns phone code hash', async () => {
    let data = await actions.submitPhoneNumber()
    await flushPromises()

    expect(data).toBeTruthy()
  })
})

Here is the solution:

index.ts :

export const actions = {
  // I don't know where you get $axios from this, you didn't give the completed code. so I made a fake one for the demo.
  $axios: {
    $get: url => ''
  },
  async submitPhoneNumber(context) {
    let data = await this.$axios.$get('https://jsonplaceholder.typicode.com/todos/1');
    // do something with data

    data = this.processData(data);
    return data;
  },

  // for demo
  processData(data) {
    return data;
  }
};

index.spec.ts :

import { actions } from './';

actions.$axios = {
  $get: jest.fn()
};

describe('actions', () => {
  it('should mock action.$axios.$get method', () => {
    expect(jest.isMockFunction(actions.$axios.$get)).toBeTruthy();
  });
  it('should get data correctly', async () => {
    (actions.$axios.$get as jest.Mock<any, any>).mockResolvedValueOnce({ userId: 1 });
    const actualValue = await actions.submitPhoneNumber({});
    expect(actualValue).toEqual({ userId: 1 });
    expect(actions.$axios.$get).toBeCalledWith('https://jsonplaceholder.typicode.com/todos/1');
  });
});

Unit tests result:

 PASS  src/mock-module/axios/index.spec.ts
  actions
    ✓ should mock action.$axios.$get method (4ms)
    ✓ should get data correctly (4ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        2.181s, estimated 3s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM