Шут зеленый, даже если ожидаемый не равен Получено - PullRequest
0 голосов
/ 15 мая 2018
it('User is already present as a supplier', (done) => {
    const store = mockStore({}, [{ type: 'get_user', data: { } }]);
    return store.dispatch(userGetAction({ role: 'supplier' }, () => {})).then(() => {
      try {
        expect(store.getActions()[0].data.disabled).toEqual(true);
        expect(store.getActions()[0].data.errormessage).toEqual('User is already present as a assitantbuyer');
      } catch (err) {
        console.log(err);
      }
      done();
    }).catch(() => {
      done();
    });
  });

Почему он проходит и показывает зеленый статус, даже если ожидается, не равен фактическому.

PASS  src/actions/user-get-action-assistant-buyer.test.jsx
  ● Console

    console.error node_modules/fbjs/lib/warning.js:33
    console.log src/actions/user-get-action-assistant-buyer.test.jsx:25
      { Error: expect(received).toEqual(expected)

      Expected value to equal:
        "User is already present"
      Received:
        "User is already present"
          at store.dispatch.then (/Users/prakashchandrabarnwal/Desktop/myProductInduct_CE_Admin/src/actions/user-get-action-assistant-buyer.test.jsx:23:57)
        matcherResult: 
         { actual: 'User is already present as a assitant buyer',
           expected: 'User is already present as a assitantbuyer',
           message: [Function],
           name: 'toEqual',
           pass: false } }

Если я не обертываю ожидание внутри, попробуйте поймать его молча внутри .catch ()

код возврата, возвращаемый UnhandledPromiseRejectionWarning:

const buyerAction = (data = {}, cb) => dispatch => axios({
  method: 'POST',
  url: `http://localhost:3001/api/manageUsers`,
  headers: {
    'x-access-token': authService.getAccessToken()
  },
  data
}).then(res => new Promise((resolve, reject) => {
  if (res.status === 200 && res.data) {
    dispatch({ type: 'buyer_created', data: res.data.message });
    if (data.role === 'buyer') {
      axios({
        method: 'POST',
        url: `http://localhost:3001/api/populateBuyerLookUp`,
        headers: {
          'x-access-token': authService.getAccessToken()
        },
        data
      })

.then((response) => {
            resolve(response);
          }).catch((err) => {
            reject(err);
          });
        }
        cb(res.data.message);
      } else {
        reject(res);
      }
    }))
      .catch(() => {
        console.log('error');
      });

(узел: 44182) UnhandledPromiseRejectionWarning: необработанное отклонение обещания. Эта ошибка возникла либо из-за того, что внутри асинхронной функции не был выполнен блок catch, либо из-за отклонения обещания, которое не было обработано с помощью .catch (). (код отклонения: 1)

1 Ответ

0 голосов
/ 15 мая 2018

Итак, ваш expect завершается с ошибкой, вы ловите эту ошибку и просто регистрируете ее, другими словами, вы отключаете ошибку. В конце концов, вы называете «готово» так же, как нет ошибки. Код делает все так, как вы написали: игнорируйте и отключайте все ошибки. Вы должны удалить все catch из вашего теста

it('User is already present as a supplier', () => {
    const store = mockStore({}, [{ type: 'get_user', data: { } }]);
    return store
       .dispatch(userGetAction({ role: 'supplier' }, () => {}))
       .then(() => {
            expect(store.getActions()[0].data.disabled).toEqual(true);
            expect(store.getActions()[0].data.errormessage).toEqual('User is already present as a assitantbuyer');
        });
  });

Вы можете вернуть Promise из своего теста (нет необходимости использовать done), а если обещание не выполнено, весь тест не пройден. это все

UPD: относительно UnhandledPromiseRejectionWarning, я думаю, что это может быть связано с вашим запросом к "populateBuyerLookUp", этот запрос полностью вне потока. Я пытался это исправить, но трудно понять, что именно вы хотите сделать

    const buyerAction = (data = {}, cb) => dispatch => axios({
  method: 'POST',
  url: `http://localhost:3001/api/manageUsers`,
  headers: {
    'x-access-token': authService.getAccessToken()
  },
  data
})
  .then((res) => {
    dispatch({type: 'buyer_created', data: res.data.message});
    let promise;
    if (data.role === 'buyer') {
      promise = axios({
        method: 'POST',
        url: `http://localhost:3001/api/populateBuyerLookUp`,
        headers: {
          'x-access-token': authService.getAccessToken()
        },
        data
      });
    }

    return Promise.resolve(promise).then(() => res.data.message);
  })
  .then((message) => {
    cb(message)
  }).catch(()=>{console.log("error")});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...