Mal*_*ous 14 javascript jestjs
我遇到一种情况,我需要创建一个调用函数并检查其返回值的测试。它返回一个对象,因此我必须迭代它并检查 100 个左右的值的正确性。如果其中之一失败了,我想知道是哪一个。
我无法弄清楚如何使用普通 Jest 来执行此操作,以便测试是独立的,并且在失败时我会收到有意义的错误消息。
例如,我可以这样做:(用于说明的伪代码,而不是实际代码)
describe('Test for function A', () => {
beforeAll('Create class instance', () => {
this.inst = new MyClass();
});
test('Call function with no parameters', () => {
const value = this.inst.run();
for (each key=value) {
expect(value).toBe(correct); // on failure, doesn't tell me the key, only the value
}
});
});
Run Code Online (Sandbox Code Playgroud)
这样做的问题是,如果value不是correct,那么错误消息不是很有帮助,因为它没有告诉我 100 个值中的哪一个有问题。
我无法更改为,test.each()因为然后我收到一条错误消息,指出我有test()不允许的嵌套调用。
如果我使用内部test()并将父级更改test()为,describe()那么代码将变为:
describe('Test for function A', () => {
beforeAll('Create class instance', () => {
this.inst = new MyClass();
});
describe('Call function with no parameters', () => {
const value = this.inst.run();
for (each value) {
test(`Checking ${value.name}`, () => {
expect(value).toBe(correct);
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
这会给我一个详细的错误消息,除了this.inst.run()在测试设置期间调用,之前this.inst已由 设置beforeAll(),因此它失败。(Jestdescribe()首先运行所有块,然后运行beforeAll(),然后运行test()。这意味着我在块创建类实例之前this.inst.run()首先在该块中调用。)describe()beforeAll()
有什么办法可以实现这一点吗?要进行一个需要创建一个对象并在所有子测试之间共享的测试,一个调用函数来获取该组数据的测试组,然后是该组内的一堆测试?
lis*_*tdm 10
describe是的,根据和块的执行顺序是可以的test:
describe("Test for function A", () => {
this.inst = new MyClass();
afterAll("Create class instance", () => { //--> use this instead of beforeAll
this.inst = new MyClass();
});
test("Should be defined", () => {
//--> at least one test inside describe
expect(inst).toBeTruthy();
});
describe("Call function with no parameters", () => {
const value = this.inst.run();
test("Should be defined", () => {
//--> at least one test inside describe
expect(value).toBeTruthy();
});
for (/*...each value */) {
test(`Checking ${value.name}`, () => {
expect(value).toBe(correct);
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25337 次 |
| 最近记录: |