`nock.js`基于输入模拟响应

时间:2019-10-15 02:52:47

标签: javascript node.js mocking nock

我有相同的API终结点,它将根据获取的输入返回不同的响应。 我正在尝试为我的UI测试模拟API。

所以基本上在我的UI测试中:

单击UI中的按钮--->在后端使用有效负载1调用虚拟API->虚拟API给出响应1(这是输入有效负载)--->调用相同的虚拟API --->获取响应2-> UI操作根据响应发生

我需要模拟API响应,这就是我尝试过的

    // button to click that triggers the API endpoint 
    $('action').click();

    // this is the mock API that checks if the input payload has the word `INPUT1`
    // reponse expected from the dummy API is stored in  `response1.xml` 

    let scope = nock('http://localhost:4002')
        .post('/', /INPUT1\\/)
        .reply(200, (uri, requestBody) => {
            console.log('uri', uri)
            console.log('requestbody', requestBody)
            fs.readFile(join(process.cwd(), 'test', 'response1.xml')) 
        })


    // dummy  API called again with prev nock response
    // input payload is data in file `response1.xml` 
    // should check if the input payload has the word `INPUT2\`
    // mocked output for the API is in file response2.xml

    nock('http://localhost:4002')
        .post('/', /INPUT2\\/)
        .reply(200, (uri, requestBody) => {
            fs.readFile(join(process.cwd(), 'test/', 'response2.xml')) 
        })
    // when the app sees response response2.xml, "done" button appears on screen
    // click on `done` button
    $('#done).click

当我尝试此操作时,它没有说API not reachable。不知道我是否在正确模拟API。我尝试模拟的API是虚拟API。诺克有可能吗?

0 个答案:

没有答案