环境:
NodeJS 8.1.2
axios 0.16.2
axios-mock-adapter 1.9.0使用JSONPlaceholder的测试POST应用程序接口调用如下:
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数据?
发布于 2019-08-21 04:19:30
您可以捕获对特定POST的所有URL请求,然后在reply回调和passThrough中手动匹配您的条件。如果条件不满足,我们可以在reply回调中通过将调用传递给other question中的passThrough来应答。
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实现,您不能向相同的URL和method添加另一个请求,您必须添加逻辑以将所有需要的情况匹配到一个请求。
发布于 2021-03-29 22:45:15
从v1.18.0 (2020年3月22日)开始支持asymmetricMatch。
mockHttpClient.onPost(/(\/comments)/i, {
asymmetricMatch: (actual) => actual.email === 'authorA@test.com'
}).reply(527)https://stackoverflow.com/questions/46638153
复制相似问题