如何在 Ember.js 中存根任务?

我正在将 Sinon 与 Ember.js 并发任务一起使用,并尝试在测试中存根该任务。


代码如下所示:


组件文件:.ts


import Component from '@glimmer/component';

import { TaskGenerator, TaskInstance } from 'ember-concurrency';

import { task } from 'ember-concurrency-decorators';

import { taskFor } from 'ember-concurrency-ts';


export default class Container extends Component<Args> {


    @task *myTask(): TaskGenerator<Data> {

        const response: Data = yield json('someURL'); //json() returns a JSON object from a request to someURL

        return response;

    }


    get task(): TaskInstance<Data> | null {

        const task = taskFor(this.myTask);

        return task.last ? task.last : task.perform();

    }


    @action

    someMethod(): void {

        const task = taskFor(this.myTask);

        task.perform();

    }

}

组件测试文件中的相关测试:


...

module('Integration | Component | container', function(hooks){

    test('some test', async function(this: Context, assert) {

    await render(hbs`

        <Container @someMethod={{@someArgument}} as |c| >

            // some code that uses c

        </Container>

    `);

}

如何存根myTask任务?我基本上希望拥有它,以便我能够手动控制来自 myTask 的响应,这样就不必在测试中做出 HTTP 响应。


烙印99
浏览 40回答 3
3回答

慕的地6264312

我会用你的模拟任务覆盖真实的任务来扩展你的测试文件中的组件。class TestContainer extends Container {&nbsp; @task *myTask(): TaskGenerator<Data> {&nbsp; &nbsp; return someMockData;&nbsp; }}// ...hooks.beforeEach(function() {&nbsp; this.owner.register('component:container', TestContainer);});

开心每一天1111

我不知道有什么方法可以模拟组件中的单个任务进行测试。当涉及网络时,我会伸手去寻找建立在伪装者之上的 ember-cli-mirage。Mirage 在处理 ember-data 模型时非常出色,也可用于处理模拟任何网络请求。如果您不使用 ember-data,您可能只想使用伪装者或调查非框架 Mirage.js。通过模拟网络并返回预制数据,您将在测试组件时对测试进行相同的控制。我真的很喜欢这种方法,并且发现它多年来一直非常可靠和稳定。

守着星空守着你

在我的项目中,我确实有使用 sinon 的任务存根。它的构建方式与你的设置略有不同,但也许你可能会得到一些灵感。所以我在我的组件中有这个任务&nbsp; @(task(function* () {&nbsp; &nbsp; &nbsp; yield this.exportxls.asXls.perform(someArg);&nbsp; })) downloadXls;此方法在服务中asXls&nbsp; @(task(function* (mapping) {&nbsp; &nbsp; // ...&nbsp; }).drop()) asXls;然后在我的集成测试中,我像这样做存根&nbsp; &nbsp; this.owner.register('service:exportxls', Service.extend({&nbsp; &nbsp; &nbsp; init() {&nbsp; &nbsp; &nbsp; &nbsp; this._super(...arguments);&nbsp; &nbsp; &nbsp; &nbsp; this.set('asXls', {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; perform: sinon.stub()&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }));在那之后,我可以进行常规检查&nbsp; &nbsp; assert.ok(exportService.asXls.perform.calledOnce);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript