代码之家  ›  专栏  ›  技术社区  ›  nhrcpt

提取JSON数据并使用量角器验证该值

  •  -1
  • nhrcpt  · 技术社区  · 6 年前

    我需要从JSON文件中读取数据,然后断言其键的值与其他一些值匹配。以下是我的示例代码:

    var fs = require('fs');
    
    let StudentData = 'StudentData.json';
    
    describe('Test for Json Data', function (){
    
        let Data = {
    
            a: 'a',
            b: 'bb',
            c: 'ccc'
        };
    
        let DT = JSON.stringify(Data);
    
        fs.writeFileSync(StudentData ,DT)
    
    
        it('test for C', function(){
    
            let Uploaded_data = fs.readFileSync(StudentData);
    
            let Data = JSON.parse(Uploaded_data);
    
            let c = Data['c'];
    
            console.log(c);
    
            expect(c.toBe('ccc'));
    
        })
    
    });
    

    当我运行脚本时,我得到以下错误:

     1) Test for Json Data test for C
      Message:
        Failed: c.toBe is not a function
      Stack:
        TypeError: c.toBe is not a function
    

    这里如何验证“c”的值?

    1 回复  |  直到 6 年前
        1
  •  1
  •   craig    6 年前

    我同意你应该 expect(c).toBe(...) .还有一些其他的事情要小心。我会把你想要的方法放在 it A块 beforeAll beforeEach 方法以确保它们在IT块之前执行。

    在清理它的同时,@jornsharpe的评论,我将执行以下操作:

    const fs = require('fs');
    const studentData = 'StudentData.json';
    
    describe('Test for Json Data', () => {
      const data = {
        a: 'a',
        b: 'bb',
        c: 'ccc'
      };
    
      beforeAll(() => {
        // make sure that you specify this in beforeAll or beforeEach
        fs.writeFileSync(studentData ,JSON.stringify(data))
      });
    
      it('test for C', () => {
        const uploadedData = fs.readFileSync(StudentData);
        const parsedData = JSON.parse(uploadedData);
        const c = parsedData['c'];
        console.log(c);
        expect(c)toBe('ccc'));
      });
    });