Reputation: 97
Im trying to test something and I cant lead to the solution
const Config = require('client-config')
const cfgM = Config.CFGBuilder.builder().build();
class ConfigService {
static get(key) {
return cfgM.getProperty(key);
}
}
module.exports = ConfigService;
This is what im trying to test. The get
from my configManager.
const Config = require('my-config');
const { expect } = chai;
const ConfigService = require('../ConfigService');
jest.mock('my-config', () => ({
CFGBuilder:
{
builder: () => ({
build: () => ({
getProperty: jest.fn(),
}),
}),
},
}));
describe('testing config service', () => {
describe('testing get', () => {
it('should return db.name', () => {
Config.CFGBuilder.builder().build().getProperty.mockImplementation(key => 'mykey');
expect(ConfigService.get('key')).to.be('mykey');
});
});
});
The thing is im getting undefined from the ConfigServivce.get('key')
Disclaimer: I didn't code the client-config module. It's just a module I must use
Upvotes: 1
Views: 1911
Reputation: 102497
You didn't mock a return value or implementation for cfgM.getProperty ()
, that's why you got undefined
. For chain calls of methods, you can use .mockReturnThis()
instead of return a nested object.
Here is unit test solution:
index.js
:
const Config = require('client-config');
const cfgM = Config.CFGBuilder.builder().build();
class ConfigService {
static get(key) {
return cfgM.getProperty(key);
}
}
module.exports = ConfigService;
index.test.js
:
const Config = require('client-config');
const ConfigService = require('./');
jest.mock(
'client-config',
() => ({
CFGBuilder: {
builder: jest.fn().mockReturnThis(),
build: jest.fn().mockReturnThis(),
getProperty: jest.fn(),
},
}),
{ virtual: true },
);
describe('testing config service', () => {
describe('testing get', () => {
it('should return db.name', () => {
Config.CFGBuilder.builder()
.build()
.getProperty.mockImplementation((key) => 'mykey');
expect(ConfigService.get('key')).toBe('mykey');
});
});
});
unit test result with 100% coverage:
PASS stackoverflow/63198582/index.test.js (13.614s)
testing config service
testing get
✓ should return db.name (3ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.747s, estimated 18s
Upvotes: 4