【问题标题】:express api for test with jest用 jest 表示用于测试的 api
【发布时间】:2022-07-20 17:23:31
【问题描述】:

如何用express编写rest api来用jest检查js代码?

import shell from 'shelljs'
import path from 'path'

export const checkTask = (req, res) => {
    shell.touch('./task.test.js')
    shell.ShellString(`const getSum = (a, b) => a + b\ntest('sum of 4 and 5 expected to be 9', () => { const data = getSum(4, 5); expect(data).toBe(9); })`).to('./task.test.js')
    shell.exec('npm run test')

    res.status(200).json({
        'ok': true
    })
}

它不返回任何东西,它只是创建测试文件但不运行 jest,所以我无法得到结果。终端中没有错误消息

如果我像下面这样单独运行,它可以工作

export const checkTask = (req, res) => {
    shell.touch('./task.test.js')
    shell.ShellString(`const getSum = (a, b) => a + b\ntest('sum of 4 and 5 expected to be 9', () => { const data = getSum(4, 5); expect(data).toBe(9); })`).to('./task.test.js')

    res.status(200).json({
        'ok': true
    })
}

或者像这样与已经创建的测试文件一样,它也可以工作

export const checkTask = (req, res) => {
    shell.exec('npm run test')

    res.status(200).json({
        'ok': true
    })
}

【问题讨论】:

    标签: javascript node.js express jestjs shelljs


    【解决方案1】:

    我用 shelljs

    解决了这个问题
    shell.touch(path)        
    shell.ShellString(`${req.body.solution}\n${req.body.tests}`).to('./task.test.js')
    var child = shell.exec('npm run test', {async: true, silent: true})
    child.stdout.on('data', () => { })
    

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2016-10-09
      • 2021-10-16
      • 2020-12-10
      • 2020-09-25
      • 2017-01-24
      • 2021-02-03
      • 2019-10-01
      • 1970-01-01
      相关资源
      最近更新 更多