Node.js Jest单元测试单例类Nodejs

Node.js Jest单元测试单例类Nodejs,node.js,unit-testing,jestjs,mocking,singleton,Node.js,Unit Testing,Jestjs,Mocking,Singleton,我在下面的代码中尝试对使用singleton类的类变量的函数进行单元测试 Singletonclass a.js class A{ constructor(){ this.flag = true; } setA(){ this.flag=false; } } module.exports = new A(); //Singleton import A from './a'; class B { constructor() {} hello() { if

我在下面的代码中尝试对使用singleton类的类变量的函数进行单元测试

Singletonclass a.js

class A{
constructor(){
   this.flag = true;
 }
 
setA(){
  this.flag=false;
  }
}

module.exports = new A(); //Singleton
import A from './a';

class B {
  constructor() {}

  hello() {
    if (A.flag) {
      console.log('1');
    } else {
      console.log('2');
    }
  }
}
import A from './a' //Singleton class
import B from './'

describe('Test Hello', () => {
    const b= new B();
    
    beforeEach(() => {      
    });

    afterEach(() => {
        jest.restoreAllMocks();
    })


    test('Test Hello', async () => {        
        try{
            jest.spyOn(A, 'flag')
                .mockResolvedValueOnce(true);
            let output = b.hello();
                    
        }catch(e){
            console.log('Error', e);
        }
    });
});

使用单例类的类

class A{
constructor(){
   this.flag = true;
 }
 
setA(){
  this.flag=false;
  }
}

module.exports = new A(); //Singleton
import A from './a';

class B {
  constructor() {}

  hello() {
    if (A.flag) {
      console.log('1');
    } else {
      console.log('2');
    }
  }
}
import A from './a' //Singleton class
import B from './'

describe('Test Hello', () => {
    const b= new B();
    
    beforeEach(() => {      
    });

    afterEach(() => {
        jest.restoreAllMocks();
    })


    test('Test Hello', async () => {        
        try{
            jest.spyOn(A, 'flag')
                .mockResolvedValueOnce(true);
            let output = b.hello();
                    
        }catch(e){
            console.log('Error', e);
        }
    });
});

b.test.js的单元测试用例

class A{
constructor(){
   this.flag = true;
 }
 
setA(){
  this.flag=false;
  }
}

module.exports = new A(); //Singleton
import A from './a';

class B {
  constructor() {}

  hello() {
    if (A.flag) {
      console.log('1');
    } else {
      console.log('2');
    }
  }
}
import A from './a' //Singleton class
import B from './'

describe('Test Hello', () => {
    const b= new B();
    
    beforeEach(() => {      
    });

    afterEach(() => {
        jest.restoreAllMocks();
    })


    test('Test Hello', async () => {        
        try{
            jest.spyOn(A, 'flag')
                .mockResolvedValueOnce(true);
            let output = b.hello();
                    
        }catch(e){
            console.log('Error', e);
        }
    });
});


因此,b.js中的一行console.log(1)没有包含在覆盖率报告中。尝试了多个选项

您的代码存在许多问题:

  • 您正在测试
    b.js
    模块,而不是
    a.js
    模块。所以测试文件名应该是
    b.test.js

  • 导入的模块名称错误。它应该是
    /a.js
    ,而不是
    a.js

  • 如果要更改实例a的属性,只需指定值​​在测试用例中

  • 例如

    a.js

    A类{
    构造函数(){
    this.flag=true;
    }
    刚毛(){
    this.flag=false;
    }
    }
    module.exports=新的A()//独生子女
    
    b.js

    从“/a”导入a;
    B类出口{
    构造函数(){}
    你好(){
    如果(a.标志){
    console.log('1');
    }否则{
    console.log('2');
    }
    }
    }
    
    b.test.js

    从“/a”导入a;
    从“./B”导入{B};
    描述('67335501',()=>{
    之后(()=>{
    开玩笑。恢复记忆();
    });
    它('应打印“1”,()=>{
    constlogspy=jest.spyOn(控制台,'log');
    a、 flag=true;
    常数b=新的b();
    b、 你好;
    expect(logSpy).toBeCalledWith('1');
    });
    它('应打印“2”,()=>{
    constlogspy=jest.spyOn(控制台,'log');
    a、 flag=false;
    常数b=新的b();
    b、 你好;
    expect(logSpy).toBeCalledWith('2');
    });
    });
    
    单元测试结果:

     PASS  examples/67335501/b.test.js (10.808 s)
      67335501
        ✓ should print "1" (18 ms)
        ✓ should print "2" (2 ms)
    
      console.log
        1
    
          at console.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)
    
      console.log
        2
    
          at console.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |    87.5 |      100 |      75 |    87.5 |                   
     a.js     |   66.67 |      100 |      50 |   66.67 | 7                 
     b.js     |     100 |      100 |     100 |     100 |                   
    ----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       2 passed, 2 total
    Snapshots:   0 total
    Time:        12.657 s
    
    passexamples/67335501/b.test.js(10.808秒)
    67335501
    ✓ 应打印“1”(18毫秒)
    ✓ 应打印“2”(2毫秒)
    console.log
    1.
    在控制台。(node_modules/jest环境酶/node_modules/jest mock/build/index.js:866:25)
    console.log
    2.
    在控制台。(node_modules/jest环境酶/node_modules/jest mock/build/index.js:866:25)
    ----------|---------|----------|---------|---------|-------------------
    文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s
    ----------|---------|----------|---------|---------|-------------------
    所有文件| 87.5 | 100 | 75 | 87.5 |
    a、 js | 66.67 | 100 | 50 | 66.67 | 7
    b、 js | 100 | 100 | 100 | 100 |
    ----------|---------|----------|---------|---------|-------------------
    测试套件:1个通过,共1个
    测试:2次通过,共2次
    快照:共0个
    时间:12.657秒