gpt4 book ai didi

node.js - Mocha 测试用例在 Promise 获取数据之前执行

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:05 25 4
gpt4 key购买 nike

测试用例(Test1, Test2)在promise获取数据之前执行。这是文件mockExecution.js

describe('AC 1: This is suite one', ()=>
{
before((done)=>
{
promiseResp.then((data) => {
console.log("i am in the promise");
responseData = data;
process.exit(0);
}, (err) => {
console.log('promiseResp.err', err);
process.exit(1);
})
done();
})
it('Test1', (done)=>
{
expect(responseData.measure.abc).not.toBe(responseData.measure_list.abc);
done();
});

it('Test2', (done)=>
{

expect(responseData.measure.abc).not.toBe(responseData.measure_list.abc);
done();
});

});

Before block 内的 PromiseResp 不执行。因此“responseData”变量没有数据,并且抛出测试用例失败。我猜想存在一些异步时间问题,但不知道如何解决它,也不知道我应该把这个“process.exit(0)”放在哪里。下面是实际输出:

AC 1: This is suite one
I am in the before
1) Test1
2) Test2


0 passing (7ms)
2 failing

1) AC 1: This is suite one
Test1:
TypeError: Cannot read property 'measure' of undefined
at Context.it (QA/mockExecution.js:160:29)

2) AC 1: This is suite one
Test2:
TypeError: Cannot read property 'measure' of undefined
at Context.it (QA/mockExecution.js:167:29)

[process business logic and prints some logs here, i can't paste here]
finished analyzing all records
i am in the promise
npm ERR! Test failed. See above for more details.

我期望按以下顺序输出:

[process business logic and prints some logs here, I can't paste here]
finished analyzing all records
AC 1: This is suite one
I am in the before
I am in the promise
1) Test1 passed
2) Test2 paseed

最佳答案

您需要在您的then调用done分配的responseData = data:

before((done) => {
promiseResp.then((data) => {
responseData = data;
// Promise has resolved. Calling `done` to proceed to the `it` tests.
done();
})
.catch((err) => {
// Calling `done` with a truthy `err` argument, in case
// the promise fails/rejects, to fail-early the test suite.
done(err);
})
})

否则,在 Promise 实际解析并分配您的 responseData 变量之前,before 会提前结束并继续进行下一个测试。

这是一个使用 before Hook 的工作示例:

const expect = require('chai').expect

const getFooValue = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve('foo')
}, 500)
})
}

describe('#getFooValue()', function () {
let responseData

before(done => {
getFooValue().then(data => {
responseData = data
done()
})
.catch(err => {
done(err)
})
})

it('response has a value of foo', () => {
expect(responseData).to.equal('foo');
})

it('response is a String', () => {
expect(responseData).to.be.a('String');
})
})

你现在正在做的是:

  • 您定义Promise
  • 您(过早地)调用 done,Mocha 继续执行 it 测试。
  • it 测试在 responseData未定义时运行。
  • before 内的 Promise 最终解析并分配 responseData 变量。

...但那时已经太晚了。测试已经运行。

关于node.js - Mocha 测试用例在 Promise 获取数据之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53562445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com