3

我正在为 react redux 中的异步操作编写测试,为了解决我在此处简化代码的问题。这是我的动作功能:

export function updateUserAuthenticationStatus(){
return function(dispatch){
   return axios.get(getLoginStatusUrl())
        .then(response => {
               const middlewares = [thunk];
               const mockStore = configureMockStore(middlewares);
               const store = mockStore();
    return store.dispatch(updateUserAuthenticationStatus()).then(()=>{
       //expect(store.getActions()[0]).to.eql(expectedActions);
    });
            });
        }).catch(function(response){
    });
  }
}

所以问题是函数 getLoginStatusUrl() 会在 cookie 中进行几次检查并根据某些条件返回适当的 url。所以我想要模拟这个函数以返回例如 test.com 然后我可以测试我的操作如下:

it("", () => {
        **here I want to mock getLoginStatusUrl() to return test.com**
    nock("test.com")
        .get("/")
        .reply(200,"test detail");

})

在这种情况下,如何模拟 getLoginStatusUrl() 以返回 test.com?

4

2 回答 2

2

用 sinon 试试这个。

import {getLoginStatusUrl} from './some/path.js'

let stub = sinon.stub(),
opts = { call: getLoginStatusUrl() };

stub.withExactArgs().returns("somePredefinedReturnValue")
于 2017-08-13T18:44:33.780 回答
2

您不需要它专门返回 test.com。使用诸如axios-mock-adapter 之类的库。我没有亲自使用它,但我使用 fetch-mock 来模拟 fetch api 请求,因此这个概念应该完全相同。

可以说return ,(因为您没有显示它返回的内容)getLoginStatusUrl()/loginStatus

例子:

var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');

// This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);

// Mock any GET request to /users
// arguments for reply are (status, data, headers)
mock.onGet('/loginStatus').reply(200, {
  loginSuccess: true
});

axios.get('/loginStatus')
  .then(function(response) {
    console.log(response.data);
  });

示例代码未经测试,但希望您能理解。只需阅读库 README.md。

在您想要存根/模拟在这样的 axios 请求中未使用的私有导入的场景中,如果您使用诸如导入之类的 es6 语法,则可以使用 rewirebabel -plugin- rewire。

@HamedMinaee 如果您根本不知道路径,则可以执行类似的操作onGet('/'),这都在 README.md 中。在测试之后,我想他们是一种重置它的方法,这样并不是所有使用 axios 的测试都会受到它的影响。

afterEach(() => {
    // reset the axios mock here so that '/' doesn't affect all requests or something.
});
于 2017-08-13T18:40:14.137 回答