部分数据是否可以使用axios-mock-adapter与onPost()匹配?

时间:2017-10-09 02:46:10

标签: javascript axios axios-mock-adapter

环境:

NULL

使用JSONPlaceholder进行的测试POST API调用如下:

NodeJS 8.1.2
axios 0.16.2
axios-mock-adapter 1.9.0

我想知道是否有办法匹配部分const expect = require('chai').expect const MockAdapter = require('axios-mock-adapter') // Bootstrapping const PlaceholderApp = { createComment: function (author, email, message) { const options = { method: 'post', url: 'https://jsonplaceholder.typicode.com/comments', data: { name: author, email: email, body: message, } } return axios(options) } } // Mock Adapter const mockHttpClient = new MockAdapter(axios, { delayResponse: 50 }) // mockHttpClient.onPost(/(\/comments)/i, { name: 'author A', email: 'authorA@test.com', body: 'test comment' }).reply(526) // WORKS! mockHttpClient.onPost(/(\/comments)/i, { email: 'authorA@test.com' }).reply(527) //This won't work. Would like to have something like this to work tho... mockHttpClient.onAny().passThrough() // Test cases describe('PlaceholderApp.createComment', () => { it("should fail due to mock...", (resolve) => { PlaceholderApp.createComment('author A', 'authorA@test.com', 'test comment') .then((res) => { resolve() }) .catch((err) => { resolve(err) }) }) }) 数据?

2 个答案:

答案 0 :(得分:1)

您可以捕获对特定POST的所有URL请求,然后在reply回调和passThrough中手动匹配您的条件,如果条件不满足,我们可以在passThrough回调中的reply上将呼叫传递到originalAdapter,就像在您的other question中回答的那样。

mockHttpClient.onPost(/(\/comments)/i).reply((config) => {
  const data = JSON.parse(config.data);

  if (data.email == 'authorA@test.com') {
    return [200, 'response'];
  } else {
    // passThrough
    return mockHttpClient.originalAdapter(config);
  }
})

NOTE:如果提供的数据不同,您可以将多个full match数据发送到同一URL,但是对于我们自己的partial match实现,您不能添加其他请求到相同的URLmethod,则必须添加逻辑以将所有所需的个案与一个请求进行匹配。

答案 1 :(得分:0)

自 v1.18.0 版(2020 年 3 月 22 日)起支持 asymmetricMatch

mockHttpClient.onPost(/(\/comments)/i, {
  asymmetricMatch: (actual) => actual.email === 'authorA@test.com'
}).reply(527)