Jest:尽管期望/接收值不匹配,但异步测试错误地通过

Jest 中的以下测试不应通过:


const targetFile = require("../targetFile.js");

fetch = jest.fn(() => Promise.resolve('file scoped default value'));


test('diffFileFetch', () => {

  fetch.mockImplementation(() => new Promise((resolve, reject) => {

    resolve('wrong value');

  }));


  targetFile.diffFileFetch()

    .then(async data => {

      await expect(data).toEqual('correct value');

    })

    .catch(e => console.log(e, `=====e=====`));

});

catch 块触发但测试仍然通过。这是什么原因,应该如何解决?


PASS  

views/admin/__tests__/CurrentCouponListingSection.test.js

  ✓ diffFileFetch (6ms)


 console.log views/admin/__tests__/testFile.test.js:59

    { Error: expect(received).toEqual(expected) // deep equality


    Expected: "correct value"

    Received: "wrong value"

        at targetFile.diffFileFetch.then (/var/www/html/wptest2/wp-content/plugins/fvc/views/admin/__tests__/testFile.test.js:58:1)

        at <anonymous>

        at process._tickCallback (internal/process/next_tick.js:188:7)

      matcherResult: 

       { actual: 'wrong value',

         expected: 'correct value',

         message: [Function],

         name: 'toEqual',

         pass: false } } '=====e====='

也试过


从 .then() 中删除 async/await。没有不同。


白猪掌柜的
浏览 373回答 1
1回答

慕的地8271018

测试在Promise回调运行之前完成,所以它通过了......然后错误被记录下来。如果测试包含异步代码,则您需要使用done:test('diffFileFetch', done => {&nbsp; // <= use done&nbsp; fetch.mockImplementation(() => new Promise((resolve, reject) => {&nbsp; &nbsp; resolve('wrong value');&nbsp; }));&nbsp; targetFile.diffFileFetch()&nbsp; &nbsp; .then(data => {&nbsp; &nbsp; &nbsp; expect(data).toBe('correct value');&nbsp; &nbsp; &nbsp; done();&nbsp; // <= now call done&nbsp; &nbsp; })});...返回Promise:test('diffFileFetch', () => {&nbsp; fetch.mockImplementation(() => new Promise((resolve, reject) => {&nbsp; &nbsp; resolve('wrong value');&nbsp; }));&nbsp; return targetFile.diffFileFetch()&nbsp; // <= return the Promise&nbsp; &nbsp; .then(data => {&nbsp; &nbsp; &nbsp; expect(data).toBe('correct value');&nbsp; &nbsp; })});...或者使用async测试功能和await在Promise:test('diffFileFetch', async () => {&nbsp; // <= async test function&nbsp; fetch.mockImplementation(() => new Promise((resolve, reject) => {&nbsp; &nbsp; resolve('wrong value');&nbsp; }));&nbsp; const data = await targetFile.diffFileFetch()&nbsp; // <= await the Promise&nbsp; expect(data).toBe('correct value');});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript