如何从shell命令导入模拟数据

问题描述

我正在使用请求模拟并从外部文件获取json数据:

import { RequestMock } from 'testcafe';
const mockData = require('abc.json');

var mock = RequestMock()
    .onRequestTo('https://api.mycorp.com/users/id/135865')
    .respond(mockData);

fixture `My fixture`
    .page `https://mycorp.com`
    .requestHooks(mock);

test('My test',async t => { /* ... */ });

现在,我正在尝试从存储系统导入模拟数据。 假设将abc.json拉入当前目录的CLI命令是:

mysystem pull abc.json

我正在寻找执行此操作的代码。我尝试使用child_process,但我的CLI命令花了几秒钟来获取abc.json,同时执行testcafe代码

import { RequestMock } from 'testcafe';

const getData = require('child_process').exec;
getData('mysystem pull abc.json',(e,stdout,stderr)=> {
    if (e instanceof Error) {
        console.error(e);
        throw e;
    }
    console.log('stdout ',stdout);
    console.log('stderr ',stderr);
});
const mockData = require('./abc.json');
    
    var mock = RequestMock()
        .onRequestTo('https://api.mycorp.com/users/id/135865')
        .respond(mockData);
    
    fixture `My fixture`
        .page `https://mycorp.com`
        .requestHooks(mock);
    
    test('My test',async t => { /* ... */ });

我遇到了错误,那

mock is not defined.

我可以清楚地看到,一旦testcafe执行完成,我的json就被加载了。 因此,我需要一种使Shell命令先完成然后再执行testcafe代码方法

解决方法

TestCafe允许您创建异步函数来模拟数据。 请看以下文章:https://devexpress.github.io/testcafe/documentation/reference/test-api/requestmock/respond.html#a-custom-response-function

您可以修改getData函数以返回Promise,如下所示:

function getData () {
    return new Promise(resolve => {
        exec('your-api',(error,stdout,stderr) => {
            resolve(result);
        });
    });
}

在这种情况下,您可以修改RequestMock使其异步运行:

var mock = RequestMock()
    .onRequestTo('your-api')
    .respond(async (req,res) => {
        const body = await getData();
        res.setBody(body);
    });