Search code examples
rjsontestthat

testthat 'expect_equal' returns an error - it isn't true though the actual output and exepected outputs are the same


I'm writing a testscript to test whether some modifications has been done according to my logic. My exepected output and actual output are json file which are exactly the same. My aim is to check whether the actual output is equal to the expected output. First my function is this, It has to read the json file from the location and it has to replace the parentTCode characters with null as we want only numbers in the parentTCode.

LoadData = function(inputPath) {
  options(encoding = "UTF-8")
  if(file.exists(inputPath)) {
    setting = read_json(path = inputPath, simplifyVector = TRUE)
    setting$ParentTCode = stri_replace(str = setting$ParentTCode, replacement = "", fixed = "T")
  } else {
    stop(paste0("There's no setting json file at ", inputPath))
  }
  return(setting)
}

My test script is this

test_that(desc = "Test for 'LoadData' Condition 1",
          code = {
            filePath = "./Test/Data/Input/setting.json"
            expected_output = "./Test/Data/expected_output.json"
            expect_equal(LoadData(inputPath = filePath), expected_output)
            }
)

I'm confused as why this is throwing an error like this when both the actual and expected outputs are the same.

Error: LoadSettingJsonLDG(inputPath = filePath) not equal to `expected_output`.
Modes: list, character
names for target but not for current
Length mismatch: comparison on first 1 components
Component 1: 1 string mismatch

I will attach my sample of json file here.It is as follows

{
  "ParentTCode": ["T2802"],
  "Code": ["0001"],
  "DataType": ["Diva"],
  "FileExtention": [null],
  "Currency": [false],
  "OriginalUnit": [1000],
  "ExportUnit": [1000000]
}

This is the input file for LoadData function. The output would look like this

{
  "ParentTCode": ["2802"],
  "Code": ["0001"],
  "DataType": ["Diva"],
  "FileExtention": [null],
  "Currency": [false],
  "OriginalUnit": [1000],
  "ExportUnit": [1000000]
}

If anyone could help me I would be so glad. Thanks in advance.


Solution

  • The second argument to your expect_equal call is character, length 1, which is the path pointing to a file that contains what you expect your output to be. Since the first argument is a list, it should come as no surprise that a character and list are not equal.

    I think you intend to compare against the parsed contents of that file. If you replace your test with:

    test_that(desc = "Test for 'LoadData' Condition 1",
              code = {
                filePath = "./Test/Data/Input/setting.json"
                expected_output = "./Test/Data/expected_output.json"
                expect_equal(LoadData(inputPath = filePath),
                             fromJSON(expected_output))
                }
    )
    

    it should work.