开玩笑并设置默认行为

时间:2020-05-28 05:19:24

标签: javascript node.js unit-testing testing jestjs

我需要对功能进行单元测试:

const readiness = require("./readiness");

function stopProcessNewRequests(){
    readiness.setNotReady();
}

这是我的“就绪” 文件:

const state = require("./state");
const hooks = require("./hooks");

function setReady(){
    state.ready = true;
    hooks.notifyHook(state.ready);
}

function setNotReady(){
    state.ready = false;
    hooks.notifyHook(state.ready);
}

module.exports = {
    setReady, setNotReady
};

最后是 state.js 文件:


exports.ready = false;

exports.pendingRequests = {};

exports.changeStatusHooks = [];

exports.requestsInProcessNum = 0;

exports.authClient = null;
exports.webOperationsClient = null;
exports.webQueryClient = null;

如您所见,有多个链接的导入,如何模拟它们?我需要状态文件具有某些值,以便检查其是否实际更改。 这就是我所拥有的,但是状态似乎没有改变,并且测试失败。

describe('Testing processing new requests:', ()=> {
        test('should stop processing new requests:', ()=> {
            // jest.mock('../lib/grpc/readiness',);
            jest.mock('../lib/grpc/state');

            const state = require("../lib/grpc/state");
            const { stopProcessNewRequests } = require('../lib/grpc/requestsManager');

            state.ready = true;

            stopProcessNewRequests();

            expect(state.ready).toBeFalsy();
        })
    })

1 个答案:

答案 0 :(得分:1)

最好不要跨模块进行测试。这意味着要测试requestsManager模块,您应该模拟readiness模块,而不是间接的statehooks模块。此外,jest.mock应该在函数范围内使用,而应该在模块范围内使用。

例如

readiness.js

const state = require('./state');
const hooks = require('./hooks');

function setReady() {
  state.ready = true;
  hooks.notifyHook(state.ready);
}

function setNotReady() {
  state.ready = false;
  hooks.notifyHook(state.ready);
}

module.exports = {
  setReady,
  setNotReady,
};

hooks.js

function notifyHook() {}

module.exports = { notifyHook };

requestsManager.js

const readiness = require('./readiness');

function stopProcessNewRequests() {
  readiness.setNotReady();
}

module.exports = { stopProcessNewRequests };

state.js

exports.ready = false;

exports.pendingRequests = {};

exports.changeStatusHooks = [];

exports.requestsInProcessNum = 0;

exports.authClient = null;
exports.webOperationsClient = null;
exports.webQueryClient = null;

下面是测试文件:

requestsManager.test.js

const { stopProcessNewRequests } = require('./requestsManager');
const readiness = require('./readiness');

describe('62057531', () => {
  it('should pass', () => {
    const setNotReadyMock = jest.spyOn(readiness, 'setNotReady').mockReturnValueOnce();
    stopProcessNewRequests();
    expect(setNotReadyMock).toBeCalledTimes(1);
  });
});

readiness.test.js

const { setNotReady, setReady } = require('./readiness');
const hooks = require('./hooks');
const state = require('./state');

describe('62057531', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should set state to not ready', () => {
    jest.spyOn(hooks, 'notifyHook').mockReturnValueOnce();
    setNotReady();
    expect(hooks.notifyHook).toBeCalledWith(false);
    expect(state.ready).toBeFalsy();
  });

  it('should set state to ready', () => {
    jest.spyOn(hooks, 'notifyHook').mockReturnValueOnce();
    setReady();
    expect(hooks.notifyHook).toBeCalledWith(true);
    expect(state.ready).toBeTruthy();
  });
});

带有覆盖率报告的单元测试结果:

 PASS  stackoverflow/62057531/requestsManager.test.js (14.294s)
  62057531
    ✓ should pass (6ms)

 PASS  stackoverflow/62057531/readiness.test.js
  62057531
    ✓ should set state to not ready (5ms)
    ✓ should set state to ready (1ms)

--------------------|---------|----------|---------|---------|-------------------
File                | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
--------------------|---------|----------|---------|---------|-------------------
All files           |     100 |      100 |      75 |     100 |                   
 hooks.js           |     100 |      100 |       0 |     100 |                   
 readiness.js       |     100 |      100 |     100 |     100 |                   
 requestsManager.js |     100 |      100 |     100 |     100 |                   
 state.js           |     100 |      100 |     100 |     100 |                   
--------------------|---------|----------|---------|---------|-------------------
Test Suites: 2 passed, 2 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        17.288s, estimated 21s