3

环境:

NodeJS 8.1.2
axios 0.16.2
axios-mock-adapter 1.9.0

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

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)
      })
  })
})

我想知道是否有办法匹配部分POST数据?

4

2 回答 2

4

您可以捕获POST对特定的所有请求URL,然后在reply回调中手动匹配您的条件,passThrough如果条件不满足,我们可以passThroughreply回调中通过将调用传递给您在其他问题originalAdapter中回答的类似内容。

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相同的数据,但是对于我们自己的实现,您不能向相同的请求添加另一个请求,并且您必须添加逻辑以将所有想要的案例与一个请求匹配。URLpartial matchURLmethod

于 2019-08-20T20:19:30.120 回答
0

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

mockHttpClient.onPost(/(\/comments)/i, {
  asymmetricMatch: (actual) => actual.email === 'authorA@test.com'
}).reply(527)
于 2021-03-29T14:45:14.977 回答