2017-08-13 101 views
2

我正在为我的异步操作编写测试,以处理简单的代码。这里是我的动作功能:模拟在另一个函数中使用的函数

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?

回答

2

你不需要它专门返回test.com。使用库如。我没有使用它personaly,但我使用fetch-mock模拟获取api请求,使概念应该是完全一样的。

比方说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); 
    }); 

的示例代码是未经测试,但hopefuly你的想法。只要阅读库README.md。

在场景中,如果您希望对未在axios请求中使用的私有导入进行存根/模拟,则可以使用rewirebabel-plugin-rewire(如果使用es6语法(如导入))。

@HamedMinaee如果你根本不知道路径,那么你可以做一些类似于onGet('/')的事情,它都在README.md中。在测试之后,我想他们是重置这个方法的一种方式,所以不是所有使用axios的测试都会受到它的影响。

afterEach(() => { 
    // reset the axios mock here so that '/' doesn't affect all requests or something. 
}); 
+0

非常感谢您的回答,我会开始研究它并让您知道结果。只是一个问题:我有一个getLoginStatusUrl函数来获取url,我们根本不知道路径,但是在这里我们有onGet('/ loginStatus')模拟函数,我们定义路径'/ loginStatus'它如何解决这个问题? –

+0

@HamedMinaee看到编辑。 –

+0

非常感谢我正在处理它,并让你知道结果 –

1

用sinon试试这个。

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

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

stub.withExactArgs().returns("somePredefinedReturnValue") 
+0

谢谢你做这个工作,如果getLoginStatusUrl是一个私人函数? –

+0

将函数导出为类似'export function getLoginStatusUrl(){...}'的ES模块,然后将其导入到此处。我假设你在你的行动中也是这样做的。 –

+0

是的,但为了编写代码的最佳实践,出于测试目的而导出函数是个好主意吗? –

相关问题