Jest :来自另一个构造函数的模拟对象

时间:2021-04-21 12:42:37

标签: javascript unit-testing testing jestjs mocking

嗨,我有 2 个类 A 类和 B 类,A 类构造函数正在构造函数中实例化 B 类

A类有hello方法,B类有bye方法, A类方法hello调用B类方法bye, 在我的代码覆盖率中,b 类方法 bye 无法返回 null

已经嘲笑过 b 班

在 a.js 中

import b from './b';

class A {
  //Main class from which other class is instantiated in constructor

  constructor() {
    this.b = new b();
  }

  hello() {
    let someval = this.b.bye(); //want to mock this bye function with null value

    if (someval) {
      console.log('success');
    } else {
      console.log('error'); // this line code coverage is not happening
    }
  }
}

在 ./b

class B {
  bye() {
    //want to mock this method to return null
    console.log('Actual method call');
  }
}

在 a.test.js 中


import a from './a';
import b from './b';

jest.mock('./b', () => {
  return jest.fn().mockImplementation(() => {
    return {
      bye: () => {
        return null;
      },
    };
  });
});

describe('Test A Hello', () => {
  const a = new a();

  beforeEach(() => {
    // Clear all instances and calls to constructor and all methods:
  });

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

  test('Get Token-Negative', async () => {
    a.hello();
  });
});

预期结果是a类将调用hello,它将调用b类的bye,并且由于它被null模拟,它将返回null,但是mocked bye方法没有被调用

1 个答案:

答案 0 :(得分:0)

无法重现您的问题。您的代码运行良好。

例如

a.js

import b from './b';

export default class A {
  constructor() {
    this.b = new b();
  }

  hello() {
    let someval = this.b.bye();
    if (someval) {
      console.log('success');
    } else {
      console.log('error');
    }
  }
}

b.js

export default class B {
  bye() {
    console.log('Actual method call');
  }
}

a.test.js

import A from './a';

jest.mock('./b', () => {
  return jest.fn().mockImplementation(() => {
    return {
      bye: () => {
        return null;
      },
    };
  });
});

describe('Test A Hello', () => {
  const a = new A();

  test('Get Token-Negative', () => {
    a.hello();
  });
});

测试结果:

 PASS  examples/67196195/a.test.js (6.527 s)
  Test A Hello
    ✓ Get Token-Negative (15 ms)

  console.log
    error

      at A.hello (examples/67196195/a.js:13:15)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   85.71 |       50 |     100 |   85.71 |                   
 a.js     |   85.71 |       50 |     100 |   85.71 | 11                
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.049 s

覆盖 else 分支。