所以我正在尝试为我所做的 JavaScript 服务编写一些测试。我有一项服务依赖于与该对象相关的变量 - 然后我使用这些变量来让一切正常工作。我遇到的问题是 this.playerState
在测试中是 undefined
吗?我想确保 this.playerStats.contentValue
等于 'test'
。
const MyService = {
init: function(context) {
this.playerStats = {};
this.checkForContextParam(context);
},
checkForContextParam: function(context) {
if (context) {
this.playerStats.contextValue = context
this.playerStats.contextParam = 'context=' + this.playerStats.contextValue;
} else {
this.playerStats.contextValue = 'context_missing';
this.playerStats.contextParam = 'error=' + this.playerStats.contextValue;
}
},
}
export default MyService;
这是我尝试运行的测试,但由于 this.playerStats
未定义而失败
test("Check for context param", () => {
const context = {
value: 'test',
}
this.playerStats = {}
const result = MyService.checkForContextParam(context)
expect(MyService.playerStats.contextValue).toEqual('test')
});
最佳答案
这是单元测试解决方案:
service.js
:
const MyService = {
init: function(context) {
this.playerStats = {};
this.checkForContextParam(context);
},
checkForContextParam: function(context) {
if (context) {
this.playerStats.contextValue = context;
this.playerStats.contextParam = 'context=' + this.playerStats.contextValue;
} else {
this.playerStats.contextValue = 'context_missing';
this.playerStats.contextParam = 'error=' + this.playerStats.contextValue;
}
},
};
export default MyService;
service.test.js
:
import MyService from './service';
describe('MyService', () => {
beforeEach(() => {
const context = 'init';
MyService.init(context);
});
describe('#checkForContextParam', () => {
it('Check for context param', () => {
const context = 'test';
MyService.checkForContextParam(context);
expect(MyService.playerStats.contextValue).toEqual(context);
expect(MyService.playerStats.contextParam).toEqual('context=test');
});
it('context missing', () => {
MyService.checkForContextParam();
expect(MyService.playerStats.contextValue).toEqual('context_missing');
expect(MyService.playerStats.contextParam).toEqual('error=context_missing');
});
});
});
带有覆盖率报告的单元测试结果:
PASS src/stackoverflow/59566126/service.test.js (8.133s)
MyService
#checkForContextParam
✓ Check for context param (5ms)
✓ context missing (1ms)
------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
service.js | 100 | 100 | 100 | 100 | |
------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 9.338s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59566126
关于javascript - 如何使用 jest 测试 OOP JavaScript 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59566126/