Monday, 12 June 2017

Mocha cannot find file when test is run

Im trying to test my node endpoint that makes a call to another module. The utils module tries to read from a file. It works fine when I just call the endpoint but when the test runner tries to open it, it cannot find the JSON file.

app.js

const express = require('express')
const app = express()
const utils = require('./utils.js')

app.post('/', function (req, res) {      
  var state = utils.determineState();
  res.send(state);
})

utils.js

var fs = require('fs');

var determineState = function(long, lat){
    var lines = loadStatesFile();

    return lines[0];
};

function loadStatesFile(){
    var statesMap = {};
    var lines = require('fs').readFileSync("../../states.json", 'utf-8').split('\n');

    return lines;
};

module.exports = {
    determineState: determineState
};

appTest.js

describe('POST / ', () => {
        it('should response with 200', (done) => {
            chai.request(app).post('/')
            .end((err, res) => {
                expect(res.statusCode).to.equal(200);
                done();
            });
        });
    });
});

Whenever I run this test Im getting an error on the readFilesSync line. Error: ENOENT: no such file or directory, open '../../states.json'

Any ideas on how I can have the test find and open that file? It works fine when I run the app normally.



via Kierchon

No comments:

Post a Comment