简体   繁体   中英

express api for test with jest

How to write rest api with express for checking js code with jest?

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

It doesn't return anything, it just creates test file but doesn't run jest so i can't get results. No error messages in terminal

if i run separately like below it works

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

or like this with already created test file it also works

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

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

I solved this problem with 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', () => { })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM