0

试图测试我的http请求,但实际上从服务器获取可以每秒更新的数据。所以,我nock用来模拟请求,我的请求看起来像:

nock('http://localhost:8080')
      .get('/api/getbalance')
      .reply(200, { body: balance });

平衡是我的数据,它看起来像:

{
    "account": {
        "name": "Jack Torrance",
        "iban": "HTB0001234567",
        "balance": 3133.56
    },
    "currency": "EURO",
    "debitsAndCredits": [
        {
            "from": "Wendy",
            "description": "Diner",
            "amount": 10.50,
            "date": "2016-01-10T09:20:00.000Z"
        },

但是如果在服务器上这个数据会更新——我会收到比我在前端测试中写的另一个数据。有什么方法可以解决我的问题?

我的测试用例:

import nock from 'nock';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as actions from './';
import * as types from '../constants';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

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

  it('creates FETCH_BALANCE_SUCCEESS when fetching balance has been done', () => {
    const store = mockStore({});

    const balance = {
      account: {
        name: 'Jack Torrance',
        iban: 'HTB0001234567',
        balance: 3133.56,
      },
      currency: 'EURO',
      debitsAndCredits: [
        {
          from: 'Wendy',
          description: 'Diner',
          amount: 10.5,
          date: '2016-01-10T09:20:00.000Z',
        },
      ],
    };

    nock('http://localhost:8080')
      .get('/api/getbalance')
      .reply(200, { body: balance });

    const expectedActions = [
      { type: types.FETCH_BALANCE_REQUEST },
      { type: types.FETCH_BALANCE_SUCCEESS, balance },
    ];

    return store.dispatch(actions.fetchBalance()).then(() => {
      expect(store.getActions()).toEqual(expectedActions);
    });
  });
});

升级版:

我使用此示例http://redux.js.org/docs/recipes/WritingTests.html#async-action-creators测试是否触发了这些操作。问题就在这里expect(store.getActions()).toEqual(expectedActions);。之后我做actions.fetchBalance()store.getActions()不一样,expectedActions因为服务器上的余额发生了变化。

测试预计会收到:

  [ { type: types.FETCH_BALANCE_REQUEST },
  { type: types.FETCH_BALANCE_SUCCEESS, {
  account: {
    name: 'Jack Torrance',
    iban: 'HTB0001234567',
    balance: 3133.56,
  },
  currency: 'EURO',
  debitsAndCredits: [
    {
      from: 'Wendy',
      description: 'Diner',
      amount: 10.5,
      date: '2016-01-10T09:20:00.000Z',
    },
  ],
} },
];

但是因为服务器上的数据发生了变化,我可以收到另一个数据:

   [ { type: types.FETCH_BALANCE_REQUEST },
  { type: types.FETCH_BALANCE_SUCCEESS, {
      name: 'Jack Torrance',
      iban: 'HTB0001234567',
      balance: 128.89,
    },
    currency: 'EURO',
    debitsAndCredits: [
      {
        to: 'Billy',
        description: 'Breakfast',
        amount: 11.15,
        date: '2016-11-10T09:20:00.000Z',
      },
    ],
  }
} }
];
4

0 回答 0