logo
down
shadow

Vue.js unit test - mock service with async data


Vue.js unit test - mock service with async data

By : Jector
Date : November 21 2020, 03:00 PM
This might help you I truly couldn't figure out why sometimes the component failed to mount. I'm not even sure it's related to the injector but, in any case, I kept the test consistent by not using it; trying a different approach instead.
The component might be more testable if the service is injected through the props instead of being directly used.
code :
<template>
  <div>
  <h1>{{ message }}</h1>
</div>
</template>

<script>
  import service from './test.service'

  export default {
    name: 'HelloWorld',
    created () {
      this.service.getMessage().then(message => {
        this.message = message
      })
    },
    data () {
      return {
        message: 'A'
      }
    },
    props: {
      service: {
        default: service
      }
    }
  }
</script>
<style scoped>
</style>
import Vue from 'vue'

import Async from '@/components/Async'

const service = {
  getMessage () {
    return new Promise((resolve, reject) => {
      resolve('C')
    })
  }
}

describe('Async.vue', () => {
  let vm
  before(() => {
    const Constructor = Vue.extend(Async)
    vm = new Constructor({
      propsData: {
        service: service
      }
    }).$mount()
  })
  it('should render', function () {
    // Wrapping the tick inside a promise, bypassing PhantomJS's lack of support
    return (new Promise(resolve => Vue.nextTick(() => resolve()))).then(() => {
      expect(vm.$el.querySelector('h1').textContent).to.equal('C')
    })
  })
})


Share : facebook icon twitter icon
How to unit test async Redux actions to mock ajax response

How to unit test async Redux actions to mock ajax response


By : Dream Taiki
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Note: answer below is slightly outdated.
A much simpler updated approach is described here.
code :
function fetchTodosRequest() {
  return {
    type: ADD_TODOS_REQUEST
  };
}

function fetchTodosSuccess(body) {
  return {
    type: ADD_TODOS_SUCCESS,
    body
  };
}

function fetchTodosFailure(ex) {
  return {
    type: ADD_TODOS_FAILURE,
    ex
  };
}

export function fetchTodos(data) {
  return dispatch => {
    dispatch(fetchTodosRequest());
    return fetch('http://example.com/todos')
      .then(res => res.json())
      .then(json => dispatch(addTodosSuccess(json.body)))
      .catch(ex => dispatch(addTodosFailure(ex)));
  };
}
import expect from 'expect';
import { applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import * as actions from '../../actions/counter';
import * as types from '../../constants/ActionTypes';
import nock from 'nock';

const middlewares = [thunk];

/**
 * Creates a mock of Redux store with middleware.
 */
function mockStore(getState, expectedActions, onLastAction) {
  if (!Array.isArray(expectedActions)) {
    throw new Error('expectedActions should be an array of expected actions.');
  }
  if (typeof onLastAction !== 'undefined' && typeof onLastAction !== 'function') {
    throw new Error('onLastAction should either be undefined or function.');
  }

  function mockStoreWithoutMiddleware() {
    return {
      getState() {
        return typeof getState === 'function' ?
          getState() :
          getState;
      },

      dispatch(action) {
        const expectedAction = expectedActions.shift();
        expect(action).toEqual(expectedAction);
        if (onLastAction && !expectedActions.length) {
          onLastAction();
        }
        return action;
      }
    }
  }

  const mockStoreWithMiddleware = applyMiddleware(
    ...middlewares
  )(mockStoreWithoutMiddleware);

  return mockStoreWithMiddleware();
}

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll();
  });

  it('creates FETCH_TODO_SUCCESS when fetching todos has been done', (done) => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { todos: ['do something'] });

    const expectedActions = [
      { type: types.FETCH_TODO_REQUEST },
      { type: types.FETCH_TODO_SUCCESS, body: { todos: ['do something']  } }
    ]
    const store = mockStore({ todos: [] }, expectedActions, done);
    store.dispatch(actions.fetchTodos());
  });
});
How to mock AngularFire 2 service in unit test?

How to mock AngularFire 2 service in unit test?


By : DmytroNikishin
Date : March 29 2020, 07:55 AM
will be helpful for those in need I'm trying to set up unit tests for a sample Angular 2 app using AngularFire 2 auth, the component is fairly simple: , In this snippet:
code :
beforeEach(() => addProviders([
  AppComponent,
  AngularFire
]);
class AngularFireAuthMock extends AngularFireAuth {           // added this class
  public login() { ... }
  public logout() { ... }
}

class AngularFireMock extends AngularFire {                   // added this class
  public auth: AngularFireAuthMock;
}

beforeEach(() => addProviders([
  AppComponent,
  { provide: AngularFire, useClass: AngularFireMock }         // changed this line
]);
Angular2 Unit Test Not Using Mock Service

Angular2 Unit Test Not Using Mock Service


By : NTS2203
Date : March 29 2020, 07:55 AM
Hope that helps I am testing a very simple component that shows/hides the login/out buttons.
code :
beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FacebookLoginComponent ],
      // providers: [{ provide: AuthService, useValue: MockAuthService }]
    })
      .compileComponents();

    TestBed.overrideComponent(FacebookLoginComponent, {
      set: {
        providers: [{ provide: AuthService, useClass: MockAuthService }]
      }
    })
  }));
  // providers: [{ provide: AuthService, useValue: MockAuthService }]
beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FacebookLoginComponent ],
      providers: [{ provide: AuthService, useClass: MockAuthService }]
    }).compileComponents();
  }));
inject([ AuthService ], (service: MockAuthService) => { /* ... */ });
Spring - Unit Test with Mock - How to mock a Custom Collector in a Service unit test

Spring - Unit Test with Mock - How to mock a Custom Collector in a Service unit test


By : user3211753
Date : March 29 2020, 07:55 AM
I wish this help you The idea behind unit testing is that you atomically test your methods. But that does not mean you will have to mock every other method call inside.
Say, you have a database call/network call, it makes sense to mock it. It makes sense to mock when the response of your called method decides the branch that will be executed on your called method. But in this case, it's analogous to mocking a Collectors.toList(). There is no harm in not mocking it here.
How to mock Spring Data and unit test service

How to mock Spring Data and unit test service


By : song.chenghao
Date : March 29 2020, 07:55 AM
To fix the issue you can do For Spring Data repositories you need to specifiy the bean name. Mocking via type doesn't seem to work because the repository is a dynamic proxy at runtime.
The default bean name for PersonRepository is "personRepository", so this should work:
shadow
Privacy Policy - Terms - Contact Us © voile276.org